HDU1171:Big Event in HDU(多重背包分析)

时间:2022-03-19 18:39:34

通过分析,要使A>=B并且差值最小。所以只要使sum/2的容量下,B最大就Ok了

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
#define N 5000000
int dp[N];
struct Node{
int v,m;
}num[];
bool cmp(Node a,Node b){
return a.v<b.v;
}
int main(void)
{
int n;
int i,j,k;
while(cin>>n&&n>){
int sum=;
for(i=;i<=n;i++){
cin>>num[i].v>>num[i].m;
sum+=num[i].v*num[i].m;
}
sort(num+,num++n,cmp);
memset(dp,,sizeof(dp));
for(i=;i<=n;i++)
for(j=;j<=num[i].m;j++)
for(k=sum/;k>=num[i].v;k--){
dp[k]=max(dp[k],dp[k-num[i].v]+num[i].v);
}
cout<<sum-dp[sum/]<<" "<<dp[sum/]<<endl; }
return ;
}