Piggy-Bank
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 2940 Accepted Submission(s): 1452
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!
基本上就是一個裸模板,不過是把最大值換成最小值而已,我們要注意,因爲要求最小值,所以我們的初始值應該是一個很大的數,而且在第一次操作的時候,應該把第一個物品之前的重量的價值變爲0,否則全部都是一個大數,求不了的。
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <cstdio>
#include <stack>
using namespace std;
struct node
{
int v;
int w;
}a[1009];
int dp[10009];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int x,y,c,i,j,k,n;
scanf("%d%d",&x,&y);
c=y-x;
scanf("%d",&n);
for(i=0; i<=n-1; i++)
{
scanf("%d%d",&a[i].v,&a[i].w);
}
for(i=0;i<=c;i++) dp[i]=99999999;
for(i=0; i<=n-1; i++)
{
if(i==0) for(j=0;j<=a[i].w-1;j++) dp[i]=0;
for(j=a[i].w; j<=c; j++)
{
dp[j]=min(dp[j],dp[j-a[i].w]+a[i].v);
//printf("%d ",dp[j]);
}
//printf("----\n");
}
if(dp[c]!=99999999)printf("The minimum amount of money in the piggy-bank is %d.\n",dp[c]);
else printf("This is impossible.\n");
}
}