可以用多重背包
可以用母函数
#include <iostream>
using namespace std;
int c1[250010], c2[250010];
int value[55];
int amount[55];
int main()
{
int nNum;
while(scanf("%d", &nNum) && nNum>0)
{
memset(value, 0, sizeof(value));
memset(amount, 0, sizeof(amount));
int sum = 0;
for(int i=1; i<=nNum; ++i)
{
scanf("%d %d", &value[i], &amount[i]);
sum += value[i]*amount[i];
}
memset(c1, 0, sum*sizeof(c1[0]));
memset(c2, 0, sum*sizeof(c2[0]));
for(int i=0; i<=value[1]*amount[1]; i+=value[1])
c1[i] = 1;
int len = value[1]*amount[1];
for(int i=2; i<=nNum; ++i)
{
for(int j=0; j<=len; ++j)
for(int k=0; k<=value[i]*amount[i]; k+=value[i])
{
c2[k+j] += c1[j];
}
len += value[i]*amount[i];
for(int j=0; j<=len; ++j)
{
c1[j] = c2[j];
c2[j] = 0;
}
}
for(int i= sum/2; i>=0; --i)
if(c1[i] != 0)
{
printf("%d %d\n", sum-i, i);
break;
}
}
return 0;
}
下面这段多重背包没有使用二进制优化;推荐 背包九讲
#include <iostream>
#include <stdio.h>
using namespace std;
int aa[130000];
int price[55];
int num[55];
int main()
{
int n;
while (cin>>n && n>0)
{
int sum=0;
memset(aa,0,130000);
memset(price,0,55);
memset(num,0,55);
for (int i=0; i<n; ++i)
{
cin>>price[i]>>num[i];
sum+=price[i]*num[i];
}
for (int i=0; i<n; ++i)
{
for (int j=0; j<num[i]; ++j)
{
for (int k=sum/2; k>=price[i]; --k)
{
aa[k]=max(aa[k],aa[k-price[i]]+price[i]);
}
}
}
cout<<sum-aa[sum/2]<<" "<<aa[sum/2]<<endl;
}
}