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.
1 #include<stdio.h>
2 #define MAX 5000000
3 int min(int a,int b)
4 {
5 return a<b?a:b;
6 }
7 int dp[MAX];
8 int main()
9 {
10 int t,e,f,n,p[510],w[510],v;
11 int i,j;
12 scanf("%d",&t);
13 while(t--)
14 {
15 dp[0]=0;
16 for(i=1;i<MAX;i++)
17 dp[i]=MAX;
18 scanf("%d%d",&e,&f);
19 v=f-e;
20 scanf("%d",&n);
21 for(i=0;i<n;i++)
22 scanf("%d%d",&p[i],&w[i]);
23 for(i=0;i<n;i++)
24 for(j=w[i];j<=v;j++) //此j循环与01背包循序相反
25 dp[j]=min(dp[j],dp[j-w[i]]+p[i]);
26 if(dp[v]==MAX)
27 printf("This is impossible.\n");
28 else
29 printf("The minimum amount of money in the piggy-bank is %d.\n",dp[v]);
30 }
31 return 0;
32 }
下图为简单的模拟dp数组的元素及其更新