题目大意:有一个存钱罐,给出它的重量和装满硬币的重量,然后给出里面装的硬币的种类数,并给出每种硬币的面值和重量,求在给定重量的条件下硬币的最小价值。
解题思路:完全背包。根据《背包九讲》,这道题目相当于要求必须装满给出的重量,因此要使dp[0]=0,同时因为求的是最小值,因此其他位置应该是正无穷。
Input
The input consists of T test cases. The number of them (T) is given on the first line of the input file. Each test case begins with a line containing two integers E and F. They indicate the weight of an empty pig and of the pig filled with coins. Both weights are given in grams. No pig will weigh more than 10 kg, that means 1 <= E <= F <= 10000. On the second line of each test case, there is an integer number N (1 <= N <= 500) that gives the number of various coins used in the given currency. Following this are exactly N lines, each specifying one coin type. These lines contain two integers each, Pand W (1 <= P <= 50000, 1 <= W <=10000). P is the value of the coin in monetary units, W is it's weight in grams.
Output
Print 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
310 11021 130 5010 11021 150 301 6210 320 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.
#include <iostream>
using namespace std;
int nCases;
int nPack, nVolume1, nVolume2, nVolume;
int weight[510], value[510];
int record[10000];
const int INF = 1000000001;
int main()
{
//freopen("input.txt", "r", stdin);
scanf("%d", &nCases);
while(nCases--)
{
scanf("%d %d", &nVolume1, &nVolume2);
nVolume = nVolume2-nVolume1;
scanf("%d", &nPack);
for(int i=0; i<nPack; ++i)
{
scanf("%d %d", &value[i], &weight[i]);
}
for(int i=0; i<=nVolume; ++i)
record[i] = INF;
record[0] = 0;
for(int i=0; i<nPack; ++i)
for(int j=weight[i]; j<=nVolume; ++j)
if(record[j]>record[j-weight[i]]+value[i])
record[j] = record[j-weight[i]]+value[i];
if(record[nVolume] == INF)
printf("This is impossible.\n");
else
printf("The minimum amount of money in the piggy-bank is %d.\n",record[nVolume]);
}
return 0;
}
using namespace std;
int nCases;
int nPack, nVolume1, nVolume2, nVolume;
int weight[510], value[510];
int record[10000];
const int INF = 1000000001;
int main()
{
//freopen("input.txt", "r", stdin);
scanf("%d", &nCases);
while(nCases--)
{
scanf("%d %d", &nVolume1, &nVolume2);
nVolume = nVolume2-nVolume1;
scanf("%d", &nPack);
for(int i=0; i<nPack; ++i)
{
scanf("%d %d", &value[i], &weight[i]);
}
for(int i=0; i<=nVolume; ++i)
record[i] = INF;
record[0] = 0;
for(int i=0; i<nPack; ++i)
for(int j=weight[i]; j<=nVolume; ++j)
if(record[j]>record[j-weight[i]]+value[i])
record[j] = record[j-weight[i]]+value[i];
if(record[nVolume] == INF)
printf("This is impossible.\n");
else
printf("The minimum amount of money in the piggy-bank is %d.\n",record[nVolume]);
}
return 0;
}