完全背包问题_找的是最小值
Sample Input
3 10 110 2 1 1 30 50 10 110 2 1 1 50 30 1 6 2 10 3 20 4
Sample Output
The minimum amount of money in the piggy-bank is 60. The minimum amount of money in the piggy-bank is 100. This is impossible.
这题是完全背包问题,求的是最小值,那么就要在初始化时将临时数组f赋值为最大值,并f[0]=0;这样改变下循环判断条件就好了,最后如果不能完全匹配,也就是f[最大值]不变,便输出不可能。
#include<iostream>
using namespace std;
struct good
{
int c,w;
}goods[501];
int f[10009];
int main()
{
int t,e,ff,s,n,i,j;
cin>>t;
while(t--)
{
cin>>e>>ff;
s=ff-e;
for(i=0;i<=s;i++)f[i]=1000000000;
f[0]=0;
cin>>n;
for(i=0;i<n;i++)cin>>goods[i].w>>goods[i].c;
for(i=0;i<n;i++)
{
for(j=goods[i].c;j<=s;j++)
{
if(f[j]>f[j-goods[i].c]+goods[i].w)
{
f[j]=f[j-goods[i].c]+goods[i].w;
}
}
}
if(f[s]==1000000000)cout<<"This is impossible."<<endl;
else cout<<"The minimum amount of money in the piggy-bank is "<<f[s]<<"."<<endl;
}
return 0;
}
940

被折叠的 条评论
为什么被折叠?



