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.
题目意思要求最小可以是多少钱,没种硬币数量无限,可以用完全背包来计算,dp数组先清空为0,但是由于要最小,所以我们每次更新dp[i]的时候需要把dp[i]设置为最大值,然后进行状态转移,状态转移方程为dp[i] = min(dp[i-w[j]] + p[j], dp[i]);最后判断dp[v]是否是最大值,是就按不存在输出,否则按存在输出答案。
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int M = 5e5 + 10;
int p[505], w[505], dp[10005];
int main()
{
int T;
cin >> T;
while(T --)
{
int m, n, N;
cin >> m >> n;
cin >> N;
for(int i = 1; i <= N; i ++)
{
cin >> p[i] >> w[i];
}
int v = n - m;
memset(dp, 0, sizeof(dp));
//dp[0] = 0;
for(int i = 1; i <= v; i ++)
{
dp[i] = M;
for(int j = 1; j <= N; j ++)
{
if(i >= w[j])
{
//int t = dp[i-w[j]] + p[j];
dp[i] = min(dp[i-w[j]] + p[j], dp[i]);
//if(t < dp[i])
//{
// dp[i] = t;
//}
}
}
}
int ans = dp[v];
if(ans != M)
cout << "The minimum amount of money in the piggy-bank is " << ans << "." << endl;
else
cout << "This is impossible." << endl;
}
return 0;
}