题目链接
转化为01背包,将背包上限定为sum/2
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int a[5010],dp[250110];
int main()
{
//freopen("in.txt","r",stdin);
int n,sum,i,j,k,v,m;
while(scanf("%d",&n)&&n>0)
{
k=0;
sum=0;
memset(dp,0,sizeof(dp));
for(i=1;i<=n;i++)
{
scanf("%d%d",&v,&m);
while(m--)//转化成01背包
{
a[++k]=v;
sum+=v;
}
}
for(i=1;i<=k;i++)
for(j=sum/2;j>=a[i];j--)
dp[j]=max(dp[j],dp[j-a[i]]+a[i]);
printf("%d %d\n",sum-dp[sum/2],dp[sum/2]);
}
return 0;
}