codeup问题 A: 第二题 提供测试样例

博客内容介绍了如何解决一个数组划分问题,要求找到两个子数组,使得它们的元素之和之差最小。首先,通过getline处理输入,判断是否合法。接着,使用深度优先搜索(DFS)策略,搜索所有可能的子数组组合,找到最接近总和一半的子数组。问题可以转换为01背包问题,但由于数据规模可能导致内存超限。提供了样例输入和输出,以及测试数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述
一个数组中有若干正整数,将此数组划分为两个子数组,使得两个子数组各元素之和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背包问题。但是由于测试数据比较大,所以可能会内存超限。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值