hdu 1114 Piggy-Bank 解题报告

链接http://acm.hdu.edu.cn/showproblem.php?pid=1114

本题是一道完全背包,且要求全部要装满的。关于背包的问题可以去看一下背包九讲。

 1 #include <stdio.h>
2 const int inf=0xfffffff;
3 struct Node
4 {
5 int w, v;
6 }tr[505];
7 int dp[10005];
8 inline int min( int x, int y )
9 {
10 return x<y?x:y;
11 }
12 int main( )
13 {
14 int T, a, b;
15 scanf( "%d", &T );
16 while( T -- )
17 {
18 scanf( "%d%d", &a, &b );
19 int M=b-a, N;
20 scanf( "%d", &N );
21 for( int i=0; i<N; ++ i )
22 {
23 scanf( "%d%d", &tr[i].v,&tr[i].w );
24 }
25 for( int i=0; i<=M; ++ i )
26 dp[i]=inf; //题目要求要装满,所以要inf,最大用 -inf,最小用 inf,不要求装满则赋值为0 。
27 dp[0]=0;
28 for( int i=0; i<N; ++ i )
29 {
30 for( int j=tr[i].w; j<=M; ++ j )//这是与 0 - 1 背包区别的地方。
31 {
32 dp[j]=min( dp[j], dp[j-tr[i].w]+tr[i].v);
33 }
34 }
35 if( dp[M]==inf )
36 puts( "This is impossible." );
37 else
38 printf( "The minimum amount of money in the piggy-bank is %d.\n", dp[M] );
39 }
40 return 0;
41 }

 

 

posted @ 2012-03-06 21:23  淡墨æ末央  阅读(188)  评论(0编辑  收藏  举报