HDU 1171 Big Event in HDU
http://acm.hdu.edu.cn/showproblem.php?pid=1171
01背包
#include<bits/stdc++.h> using namespace std; const int maxn = 1000*100 +100; int dp[maxn],v[5010]; void init() { memset(dp,0,sizeof(dp)); memset(v,0,sizeof(v)); } int main () { ios::sync_with_stdio(false); int n; while (cin >> n) { init(); if(n<0) break; int sum =0,size=0; for(int i=0;i<n;i++) { int x,y; cin >> x >>y; sum+=x*y; while(y--) { v[size++] = x; } } for(int i=0;i<size;i++) { for(int j=sum/2;j>=v[i];j--) dp[j] = max(dp[j],dp[j-v[i]]+v[i]); } cout<<sum-dp[sum/2]<<" "<<dp[sum/2]<<endl; } }
//多重背包也可以
#include<bits/stdc++.h> using namespace std; const int maxn = 1000*100+100; int dp[maxn],v[maxn],c[maxn]; void init() { memset(dp,0,sizeof(dp)); memset(v,0,sizeof(v)); memset(c,0,sizeof(c)); } int main () { int n; while (~scanf("%d",&n) && n>=0) { init(); int sum =0; for(int i=1;i<=n;i++) { scanf("%d %d",&v[i],&c[i]); sum+=v[i]*c[i]; } for(int i=1;i<=n;i++) { if(v[i]*c[i] > sum/2) { for(int j=v[i];j<=sum/2;j++) dp[j] = max(dp[j],dp[j-v[i]]+v[i]); } else { int k=1,t=c[i]; while (k<t) { for(int j=sum/2;j>=k*v[i];j--) dp[j] =max(dp[j],dp[j-v[i]*k]+k*v[i]); t-=k,k*=2; } for(int j=sum/2;j>=t*v[i];j--) dp[j] = max(dp[j],dp[j-t*v[i]]+t*v[i]); } } printf("%d %d\n",sum-dp[sum/2],dp[sum/2]); } }
dp[j] = max(dp[j] ,dp[j- 单个物品的价值] +单个物品的价值)