uva624 CD   01背包+输出最优解

link:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=565

用一个二维数组g[i][v]表示:当状态转移到v的时候,第i个物品是不是用到,如果用到标记1,否则标记0.

输出路径的时候,注意,从物品编号0一直到n-1.如果某个物品被用到了,g[i][v]里面的v,就要减去这个物品的体积,然后继续往下找.

 1 /*
 2  * =====================================================================================
 3  *       Filename:  cd.cpp
 4  *        Created:  04/08/2013 15:21:34
 5  *         Author:  liuxueyang (lxy), 1459917536@qq.com
 6  *   Organization:  Hunan University
 7  *
 8  * =====================================================================================
 9  */
10 
11 /*
12 ID: zypz4571
13 LANG: C++
14 TASK: cd.cpp
15 */
16 #include <iostream>
17 #include <cstdlib>
18 #include <cstdio>
19 #include <cstring>
20 #include <cmath>
21 #include <cctype>
22 #include <algorithm>
23 #include <queue>
24 #include <set>
25 #include <stack>
26 #include <map>
27 #include <list>
28 #define INF 0x3f3f3f3f
29 #define MOD 1000000007
30 #define LL long long
31 const double eps=1e-9;
32 using namespace std;
33 int V, n, c[22], f[22222], g[22][22222];
34 int main ( int argc, char *argv[] )
35 {
36 #ifndef ONLINE_JUDGE
37     freopen("in.txt", "r", stdin);
38 #endif
39     ios::sync_with_stdio(false);
40     while (cin>>V) {
41         cin>>n;
42         for (int i = 0; i < n; ++i) cin>>c[i];
43         memset(f,0,sizeof(f));
44         memset(g,0,sizeof(g));
45         for (int i = n-1; i>=0; --i) {
46             for (int v = V; v>=c[i]; --v) {
47                 if (f[v] <= f[v-c[i]]+c[i]) {
48                     f[v] = f[v-c[i]]+c[i]; g[i][v] = 1;
49                 } else g[i][v] = 0;
50             }
51         }
52         for (int i = 0, j = V; i < n; ++i) {
53             if (g[i][j]) {
54                 cout<<c[i]<<' ';
55                 j-=c[i];
56             }
57         }
58         cout<<"sum:"<<f[V]<<endl;
59     }
60         return EXIT_SUCCESS;
61 }                /* ----------  end of function main  ---------- */

再一次表示vim比codeblocks好用多了,囧

posted on 2013-08-06 10:41  aries__liu  阅读(297)  评论(0编辑  收藏  举报