[HDOJ1171]Big Event in HDU(01背包)

时间:2022-04-25 17:14:04

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1171

许多有价值的物品,有重复。问如何将他们分成两堆,使两堆价值之差最小。

对价值求和,转换成01背包,做一次,相当于一堆选物品使得最接近一半。然后这个结果和用价值和作差的结果就是两堆的价值,此时价值只差最小。

 #include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <climits>
#include <complex>
#include <fstream>
#include <cassert>
#include <cstdio>
#include <bitset>
#include <vector>
#include <deque>
#include <queue>
#include <stack>
#include <ctime>
#include <set>
#include <map>
#include <cmath> using namespace std; const int maxn = ;
int n;
int v[];
int m;
int dp[maxn]; int main() {
// freopen("in", "r", stdin);
int vv, mm;
while(~scanf("%d", &n) && n >= ) {
memset(dp, , sizeof(dp));
memset(v, , sizeof(v));
m = ;
int half = ;
for(int i = ; i < n; i++) {
scanf("%d %d", &vv, &mm);
half += vv * mm;
while(mm--) v[m++] = vv;
}
for(int i = ; i <= m; i++) {
for(int j = half / ; j >= v[i]; j--) {
dp[j] = max(dp[j], dp[j-v[i]]+v[i]);
}
}
printf("%d %d\n", half-dp[half/], dp[half/]);
}
return ;
}