题目:
But there is a big problem with piggy-banks. It is not possible to determine how much money is inside. So we might break the pig into pieces only to find out that there is not enough money. Clearly, we want to avoid this unpleasant situation. The only possibility is to weigh the piggy-bank and try to guess how many coins are inside. Assume that we are able to determine the weight of the pig exactly and that we know the weights of all coins of a given currency. Then there is some minimum amount of money in the piggy-bank that we can guarantee. Your task is to find out this worst case and determine the minimum amount of cash inside the piggy-bank. We need your help. No more prematurely broken pigs!
OutputPrint exactly one line of output for each test case. The line must contain the sentence "The minimum amount of money in the piggy-bank is X." where X is the minimum amount of money that can be achieved using coins with the given total weight. If the weight cannot be reached exactly, print a line "This is impossible.".
Sample Input
3 10 110 2 1 1 30 50 10 110 2 1 1 50 30 1 6 2 10 3 20 4Sample 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.
题意:
给出每种钱币的价值和重量,以及存钱罐空的时候和现在的重量,算出里面价值的最小值
分析:
很显然限制条件是价值,用重量最为变量,但是有一点需要注意的是,我们求得不是小于等于重量j的最小价值,而是等于j,因此就得用完全背包问题
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<iostream>
using namespace std;
#define inf 0x3f3f3f3f
int dp[10002];//c
int main()
{
int t,i,j,n,a,b,c,v[555],w[555];
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&a,&b);
c=b-a;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d %d",&v[i],&w[i]);
}
memset(dp,inf,sizeof(dp));
dp[0]=0;
for(i=0;i<n;i++)
for(j=w[i];j<=c;j++)//顺着来就是完全背包
dp[j]=min(dp[j],dp[j-w[i]]+v[i]);
if(dp[c]==inf)
printf("This is impossible.\n");
else
printf("The minimum amount of money in the piggy-bank is %d.\n",dp[c]);
}
return 0;
}