写在前面:本文记录一些背包问题(动态规划)的练习题,欢迎讨论!本系列系本人原创,如需转载或引用,请注明原作者及文章出处。本文持续更新。
描述
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!
输入
3
10 110
2
1 1
30 50
10 110
2
1 1
50 30
1 6
2
10 3
20 4
样例输出
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.
#include<iostream>
#include<algorithm>
using namespace std;
int T, e, f, totalv, n, v[510], w[510], opt[10010];
int main()
{
cin >> T;
for (int t = 0; t < T; t++)
{
cin >> e >> f;
totalv = f - e;
cin >> n;
for (int i = 1; i <= n; i++)
cin >> v[i] >> w[i];
opt[0] = 0;
for (int i = 1; i <= totalv; i++)
opt[i] = 999999;
for (int i = 1; i <= n; i++)
{
for (int j = w[i]; j <= totalv; j++)
{
opt[j] = min(opt[j], opt[j - w[i]] + v[i]);
}
}
if (opt[totalv] == 999999)
cout << "This is impossible." << endl;
else
cout << "The minimum amount of money in the piggy-bank is " << opt[totalv] << "." << endl;
}
return 0;
}