poj3628 Bookshelf 2 DP 01背包

题目链接:http://poj.org/problem?id=3628

动态规划第二题,还是纯01背包

题意:就是给出n和b,然后给出n个数,用这n个数中的某些,求出一个和,这个和是>=b的最小值,输出最小值与b的差。

分析:这里的n个物品,每个物品的重量为c[i],价值为w[i]并且c[i]==w[i],,容量为所有c[i]的和sum。只要在f[]中从头开始找,找到一个最小>=b的就是题目要的解

 1 ///2014.4.10
 2 ///poj3628
 3 
 4 #include <iostream>
 5 #include <cstdio>
 6 #include <cstring>
 7 using namespace std;
 8 
 9 int N,B;
10 int h[30];
11 int f[2000000];
12 
13 int main()
14 {
15     // freopen("in","r",stdin);
16     // freopen("out","w",stdout);
17 
18     while( cin>>N>>B ){
19         int sum = 0;
20         for(int i=1 ; i<=N ; i++){
21             cin>>h[i];
22             sum += h[i];
23         }
24         memset(f,0,sizeof(f) );
25         for(int i=1 ; i<=N ; i++){
26             for(int j=sum ; j>=1 ; j--){
27                 int a;
28                 if( j-h[i]>=0 )
29                     a = f[j-h[i]]+h[i];
30                 else
31                     a = 0;
32                 f[j] = f[j]>a? f[j]:a;
33             }
34         }
35         for(int i = sum ; ; i--){
36             if( f[i]<B ){
37                 cout<<f[i+1]-B<<endl;
38                 break;
39             }
40         }
41     }
42     return 0;
43 }

 

posted @ 2014-04-10 19:27  basement_boy  阅读(155)  评论(0编辑  收藏  举报