已知空的储钱罐和装了硬币的储钱罐的质量。然后给了n种硬币的质量和价值。
问储钱罐里最少有多少钱。
Sol:完全背包
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxm = 10000 + 10;
const int maxn = 500 + 10;
int dp[maxm];
int value[maxn];//每袋的价格
int weight[maxn];//每袋的重量
int nValue,nKind;
//完全背包,代价为cost,获得的价值为weight
void CompletePack(int cost,int weight)
{
for(int i=cost;i<=nValue;i++)
dp[i]=min(dp[i],dp[i-cost]+weight);
}
int main()
{
int T,n,m;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
nValue=m-n;
scanf("%d",&nKind);
for(int i=0;i<nKind;i++)
scanf("%d%d",&weight[i],&value[i]);
for(int i=0;i<=nValue;i++)
dp[i]=INF;
dp[0]=0;
for(int i=0;i<nKind;i++)
CompletePack(value[i],weight[i]);
if(dp[nValue]>=INF)
printf("This is impossible.\n");
else
printf("The minimum amount of money in the piggy-bank is %d.\n",dp[nValue]);
}
return 0;
}