您的位置:首页 > 其它

51Nod 1007 正整数分组

2017-09-13 20:00 288 查看
将一堆正整数分为2组,要求2组的和相差最小。
例如:1 2 3 4 5,将1 2 4分为1组,3 5分为1组,两组和相差1,是所有方案中相差最少的。

Input
第1行:一个数N,N为正整数的数量。
第2 - N+1行,N个正整数。
(N <= 100, 所有正整数的和 <= 10000)


Output
输出这个最小差


Input示例
5
1
2
3
4
5


Output示例
1


变形的01背包,哈哈

#include<bits/stdc++.h>
using namespace std;
const int maxn=10000+5;
const int INF=0x3f3f3f;
int a[maxn],dp[maxn];
//01DP
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
int n;
while(cin>>n){
int sum=0;
for(int i=0;i<n;i++){
cin>>a[i];
sum+=a[i];
}

int temp=sum/2;
memset(dp,0,sizeof dp);
for(int i=0;i<n;i++)
for(int j=temp;j>=a[i];j--)
dp[j]=max(dp[j],dp[j-a[i]]+a[i]);
cout<<abs(sum-dp[temp]-dp[temp])<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  51Nod 01背包