51nod 正整数分组

将一堆正整数分为2组,要求2组的和相差最小。

显然我们可以把所有可能组合成的数求出来。

然后从总和的中间开始往大找,找到了就是其中一个的分组,就可以求出答案了。

#include<cstdio>
#include<algorithm>
#define REP(i, a, b) for(int i = (a); i < (b); i++)
using namespace std;

const int MAXN = 11234;
int f[MAXN], w[MAXN], n, sum;

int main()
{
	f[0] = 1;
	scanf("%d", &n);
	REP(i, 0, n)
	{
		scanf("%d", &w[i]);
		sum += w[i];
	}
	REP(i, 0, n)
		for(int j = sum; j >= w[i]; j--)
			if(f[j - w[i]])
				f[j] = 1;
	for(int ans = (sum + 1) / 2; ans <= sum; ans++)
		if(f[ans])
		{
			printf("%d\n", ans - (sum - ans));
			break;
		}
	return 0;	
} 

猜你喜欢

转载自blog.csdn.net/qq_34416123/article/details/81807501