差不多是一个裸的完全背包,只是要求满容量的最小值而已。那么dp值全部初始化为inf,并且初始化一下dp[0]即可。代码如下:
1 #include <stdio.h> 2 #include <algorithm> 3 #include <string.h> 4 using namespace std; 5 const int N = 500 + 5; 6 const int W = 10000 + 5; 7 const int inf = 0x3f3f3f3f; 8 9 int dp[W]; 10 int val[N],w[N]; 11 12 int main() 13 { 14 int T; scanf("%d",&T); 15 while(T--) 16 { 17 int E, F; 18 scanf("%d%d",&E,&F); 19 F -= E; 20 int n; 21 scanf("%d",&n); 22 for(int i=1;i<=n;i++) scanf("%d%d",val+i,w+i); 23 memset(dp,inf,sizeof dp); 24 dp[0] = 0; 25 for(int i=1;i<=n;i++) 26 { 27 for(int j=w[i];j<=F;j++) 28 { 29 dp[j] = min(dp[j], dp[j-w[i]] + val[i]); 30 } 31 } 32 if(dp[F] == inf) puts("This is impossible."); 33 else printf("The minimum amount of money in the piggy-bank is %d. ",dp[F]); 34 } 35 return 0; 36 }