Before ACM can do anything, a budget must be prepared and the necessary financial support obtained. The main income for this action comes from Irreversibly Bound Money (IBM). The idea behind is simple. Whenever some ACM member has any small money, he takes all the coins and throws them into a piggy-bank. You know that this process is irreversible, the coins cannot be removed without breaking the pig. After a sufficiently long time, there should be enough cash in the piggy-bank to pay everything that needs to be paid.
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!
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!
Input
Output
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.
大概就是给你一个小猪存钱罐的重量和存满钱的重量(也就是知道内部钱币的重量),然后给你若干种钱币的重量和价值,问你在塞满钱的前提下最小的价值是多少。
这道题不告诉我是dp我一定会用贪心去做吧……大概思路是用dp[i]储存当钱币重量为i时的最小价值,然后一种一种是过去。因为是要恰好塞满,所以直接输出dp[f-e]就行,不用想太多。
一开始把dp数组初始化成0xfffffff意外地不行呢……随便换了个值。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int dp[50010];
struct c
{
int worth,weight;
}coin[510];
int main()
{
int t;
cin>>t;
while(t--)
{
int e,f,n;
cin>>e>>f>>n;
for(int i=1;i<50010;i++)
dp[i]=9999999;
for(int i=1;i<=n;i++)
scanf("%d %d",&coin[i].worth,&coin[i].weight);
dp[0]=0;
for(int i=1;i<=n;i++)
for(int j=coin[i].weight;j<=f-e;j++)
dp[j]=min(dp[j],dp[j-coin[i].weight]+coin[i].worth);
if(dp[f-e]!=9999999&&dp[f-e]!=-0x7fffffff)
printf("The minimum amount of money in the piggy-bank is %d.\n",dp[f-e]);
else
cout<<"This is impossible."<<endl;
}
return 0;
}