题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1114
思路:在背包九讲中有提到,如果是要恰好装满,那么这儿dp[]的初始化时应将dp[0]=0,由于这儿是求最小值,故应将dp[1]-dp[n]置为正无穷;若是求最大值,则置为负无穷;
View Code
1 #include<iostream> 2 const int N=550; 3 const int inf=1000000000; 4 using namespace std; 5 6 struct Node{ 7 int value,weight; 8 }node[N]; 9 int dp[N*20]; 10 int E,F,V; 11 12 13 int main(){ 14 int _case; 15 scanf("%d",&_case); 16 while(_case--){ 17 scanf("%d%d",&E,&F); 18 V=F-E; 19 int n; 20 scanf("%d",&n); 21 for(int i=0;i<n;i++){ 22 scanf("%d%d",&node[i].value,&node[i].weight); 23 } 24 for(int i=1;i<=V;i++){ 25 dp[i]=inf; 26 } 27 dp[0]=0; 28 for(int i=0;i<n;i++){ 29 for(int j=node[i].weight;j<=V;j++){ 30 dp[j]=min(dp[j],dp[j-node[i].weight]+node[i].value); 31 } 32 } 33 if(dp[V]==inf){ 34 printf("This is impossible.\n"); 35 }else 36 printf("The minimum amount of money in the piggy-bank is %d.\n",dp[V]); 37 } 38 return 0; 39 }