文章

1

粉丝

137

获赞

0

访问

8.7k

头像
01背包思路
P1419 上海交通大学机试题
发布于2021年3月2日 22:40
阅读数 8.7k

两个数组差值最小的情况是,数组A的和等于数组B的和,二者等于所有数字总和的平均数,此时差为0。可以看出其中一个数组的总和越接近平均数,则两个数组的差值越小。

所以此问题转化为选取k个数字,使其和尽可能接近平均数average,可以采用01背包的思路解决。

#include<iostream>
#include<string>
#include<vector>
using namespace std;

bool checkNum(const string& s) {
    for(int i = 0; i < s.size();i++)
        if(s[i]>'9' || s[i]<'0')
            return false;
    return true;
}

bool getNumbers(vector<int>& n, const string& s) {
    n.clear();
    int last = 0,temp = 0;
    while(last < s.size()) {
        temp = s.find(" ",last);
        if(temp == string::npos)
            break;
        string tempS = string(s,last,temp-last);
        //cout << tempS << endl;
        if(checkNum(tempS)) {
            n.push_back(stoi(tempS));
            last = temp+1;
        }
        else return false;
    }
    string tempS = string(s,last,s.size()-last);
    if(checkNum(tempS))
        n.push_back(stoi(tempS));
    else retu...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发