Piggy-Bank
http://acm.hdu.edu.cn/showproblem.php?pid=1114
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 3183 Accepted Submission(s): 1577
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!
//這是完全揹包,bag[j]表示存錢罐的容積爲j時存錢的最小值
#include<iostream>
#include<cstring>
using namespace std;
const int INF=999999999;
int bag[10005],value[505],volume[505];
int main(){
int t,V,N,e,f;
scanf("%d",&t);
while(t--){
scanf("%d%d",&e,&f);
V=f-e;
for(int i=0;i<=V;i++) //這題是求最小值,所以初始化爲最大,若是求最大值則初始化爲最小
bag[i]=INF;
bag[0]=0; //這步不要忘記哦
scanf("%d",&N);
for(int i=1;i<=N;i++)
scanf("%d%d",&value[i],&volume[i]);
for(int i=1;i<=N;i++)
for(int v=volume[i];v<=V;v++) //這裏和01揹包順序是相反的
bag[v]=min(bag[v],bag[v-volume[i]]+value[i]);
if(bag[V]==INF)
printf("This is impossible.\n");
else
printf("The minimum amount of money in the piggy-bank is %d.\n",bag[V]);
}
//system("pause");
return 0;
}