描述
小珂最近收集了些邮票,他想把其中的一些给他的好朋友小明。每张邮票上都有分值,他们想把这些邮票分成两份,并且使这两份邮票的分值和相差最小(就是小珂得到的邮票分值和与小明的差值最小),现在每张邮票的分值已经知道了,他们已经分好了,你知道最后他们得到的邮票分值和相差多少吗?
-
输入
-
第一行只有一个整数m(m<=1000),表示测试数据组数。
接下来有一个整数n(n<=1000),表示邮票的张数。
然后有n个整数Vi(Vi<=100),表示第i张邮票的分值。
输出
- 输出差值,每组输出占一行。 样例输入
-
2 5 2 6 5 8 9 3 2 1 5
样例输出
-
0 2
思路:01背包问题,邮票总价值的一半是背包容量,邮票的价值是物品。
设:dp[i][j]表示前i个物品在容量j中的最大价值。得到状态转移方程:dp[i][j] = max(dp[i-1][j],dp[i-1][j-tamp[i]]+tamp[i]);
但是这样写的会,提交后你会发现超内存了。j<=100*1000/2 i<=1000 O(MN) i*j<=50000000
既然二维数组会超内存,那么就把状态转移方程用一维数组表示,用“滚动数组的”方法可以实现。
设dp[j]是容量为j的背包能装的总价值。得到状态转移方程:dp[j] = max(dp[j],dp[j-tamp[i]]+tamp[i]);
for(int j=x ;j>=0 ;j--)
注意:j是从大小大,逆序的。
为什么这样对呢?在计算f[i][j]之前,dp[j]保存的是f[i-1][j]的数据。dp[j-tamp[i]]保存的是f[i-1][j-tamp[i]]的数据,而不是f[i][j-tamp[i]],。所以状态转移方程其实就是求的max(dp[i-1][j],dp[i-1][j-tamp]+tamp[i]);并且覆盖掉原来的dp[j]
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int m,n,stamp[1005],dp[50001];
int main(){
scanf("%d",&m);
while(m--){
scanf("%d",&n);
int sum = 0;
for(int i=1 ;i<=n ;i++){
scanf("%d",&stamp[i]);
sum+=stamp[i];
}
int x = sum/2;
memset(dp,0,sizeof(dp));
//可以边读入,变处理数据
for(int i=1 ;i<=n ;i++){
for(int j=x ;j>=0 ;j--){
if(j>=stamp[i])
dp[j] = max(dp[j],dp[j-stamp[i]]+stamp[i]);
}
}
printf("%d\n",abs(sum-2*dp[x]));
}
return 0;
}