题目描述
一个数组中有若干正整数,将此数组划分为两个子数组,使得两个子数组各元素之和a,b的差最小,对于非法输入应该输出ERROR。
输入
数组中的元素
输出
降序输出两个子数组的元素和
样例输入 Copy
10 20 30 10 10
10 20 abc 10 10
样例输出 Copy
40 40
ERROR
思路:
1.先getline处理读入的字符串,每读到一个空格,就可以判断一个子串是不是数字。如果是则存入数组之中,如果不是就error。
2.如果1步骤合法,那么开始dfs处理数组。关键:搜索每一个最小于等于sum/2的子数组,并且找出其中和最接近sum/2的子数组。
#include <iostream>
#include <cstdio>
#include <map>
#include <vector>
#include <string>
#include <memory.h>
#include <set>
#include <stack>
#include <queue>
#include <unordered_map>
#include <iomanip>
#include <algorithm>
#include <cmath>
using namespace std;
bool judge(string s) {
for (int i = 0; i < s.length(); i++) {
if (!isdigit(s[i]))
return false;
}
return true;
}
void dfs(int index, int ans, int half, int num[], int count, int &res) {
if (index == count)
return;
if (ans + num[index] <= half) {
res = max(res, ans + num[index]);//res每次存小于等于half且最接近half的子数组和。
if (res == half)//等于half最优直接返回
return;
dfs(index + 1, ans + num[index], half, num, count, res);//如果选了第index个数,和还小于half继续dfs
}
dfs(index + 1, ans, half, num, count, res);//不选第index个
}
int main() {
string s;
while (getline(cin, s)) {
//处理字符串,存入数组之中。
int pre = 0, number[1010], count = 0, sum = 0;
bool flag = true;
for (int i = 0; i < s.length(); i++) {
if (s[i] == ' ') {
string str = s.substr(pre, i - pre);
if (judge(str)) {
int temp = stoi(str);
sum += temp;
number[count++] = temp;
pre = i + 1;
}
else {
flag = false;
break;
}
}
}
string str = s.substr(pre, s.length() - pre);//判断最后一个字符串
if (judge(str)) {
int temp = stoi(str);
sum += temp;
number[count++] = temp;
}
else
flag = false;
//寻找最接近sum/2的子数组。
if (flag) {
int half = sum / 2, res = 0;
dfs(0, 0, half, number, count, res);
cout << sum - res << " " << res << endl;
}
else {
cout << "ERROR" << endl;
}
}
return 0;
}
这里给出几组测试数据:
20 20
//结果:20 20
100
//结果:100 0
460147 494206 676854 305892 325972 739461 668894 452882 640363 29397 791093 98440 992019 767406 255592 81577 85613 193524 50705
//结果:4055025 4055012
dfs递归过程可以转化为dp过程。只需要把这个问题看成给出一个数组,寻找容量为sum/2的最优解,可以看作01背包问题。但是由于测试数据比较大,所以可能会内存超限。