Piggy-Bank
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 20871 Accepted Submission(s): 10613
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!
完全揹包+最小值+恰好裝滿。
1.完全揹包,與01揹包在一維轉移方程的區別是,01揹包一維j的循環是逆序的,而完全揹包是正序的,原因是完全揹包可以取任意件,具體原因可參照揹包九講。
2.最小值,a>b?a:b換成a<b?a:b即可。
3.恰好裝滿,若是求最大值,dp數組元素初始化爲-∞;若是求最小值,初始化爲+∞,最後若dp[V]的值改變,則輸出dp[V],反之則輸出不滿足條件。若不需要恰好裝滿,則初始化爲0。
AC代碼:
#include <stdio.h>
#include <string.h>
#define min(a,b) a<b?a:b
int main()
{
int T,E,F,V,n,i,j,p[505],w[505],dp[10005];
scanf("%d",&T);
while(T--)
{
scanf("%d %d",&E,&F);
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d %d",&p[i],&w[i]);
V=F-E;
dp[0]=0;
for(i=1;i<10005;i++)
dp[i]=429496729;
for(i=0;i<n;i++)
for(j=w[i];j<=V;j++)
dp[j]=min(dp[j],dp[j-w[i]]+p[i]);
if(dp[V]<429496729)
printf("The minimum amount of money in the piggy-bank is %d.\n",dp[V]);
else
printf("This is impossible.\n");
}
return 0;
}