http://acm.hdu.edu.cn/showproblem.php?pid=1114
View Code
1 #include<stdio.h> 2 3 int main( ) 4 { 5 int cases ; 6 int f ; 7 int e ; 8 int maxVolumn ; 9 int N ; 10 int i ; 11 int j ; 12 int P[50001] ; 13 int W[10001] ; 14 int record[10001] ; 15 const int INF = 1000000001 ; 16 17 for( scanf("%d",&cases); cases>0 ; cases-- ) 18 { 19 scanf( "%d %d",&e,&f); 20 maxVolumn = f - e ; 21 scanf("%d",&N); 22 for( i = 0 ; i < N ; i++ ) 23 { 24 scanf( "%d %d",&P[i],&W[i] ); 25 } 26 27 for( i = 0 ; i <= maxVolumn ; i++ ) 28 record[i] = INF ; 29 30 record[0] = 0 ; 31 32 for( i = 0 ; i < N ; i++ ) 33 for ( j = W[i] ; j <= maxVolumn ; j++ ) 34 if( record[j] > record[j-W[i]]+P[i] ) 35 record[j] = record[j-W[i]]+P[i]; 36 37 38 39 if( record[maxVolumn] == INF ) 40 printf("This is impossible.\n"); 41 else 42 printf("The minimum amount of money in the piggy-bank is %d.\n",record[maxVolumn]); 43 } 44 return 0; 45 }
// 这是ambition神牛的版本
// 初始化为-1
View Code
1 #include<stdio.h> 2 int num[10001],w[500],v[500]; 3 main() 4 { 5 int n,m,e,f,t,i,j; 6 for(scanf("%d",&t);t>0;t--) 7 { 8 scanf("%d%d",&e,&f); 9 m=f-e; 10 for(scanf("%d",&n),i=0;i<n;i++) 11 scanf("%d%d",&v[i],&w[i]); 12 num[0]=0; 13 for(i=1;i<=m;i++) 14 num[i]=-1; 15 16 for(i=0;i<n;i++) 17 { 18 for(j=w[i];j<=m;j++) 19 { 20 if(num[j-w[i]]!=-1&&num[j]!=-1) 21 {if(num[j-w[i]]+v[i]<num[j]) num[j]=num[j-w[i]]+v[i];} 22 else if(num[j-w[i]]!=-1&&num[j]==-1) 23 {num[j]=num[j-w[i]]+v[i];} 24 } 25 } 26 if(num[m]!=-1) 27 printf("The minimum amount of money in the piggy-bank is %d.\n",num[m]); 28 else 29 printf("This is impossible.\n"); 30 } 31 return 0; 32 }