UVa 624 CD(01背包并打印)
第一次做把选择的打印出来的背包题目,于是还是更新下,把代码贴出来。
题目很简单,为了让打印更加顺利,选择从后往前选择物品。
#include <cstdio> #include <cstdlib> #include <cstring> const int MAXN = 10010; int dp[MAXN]; int time[25]; bool f[25][MAXN]; int main() { int w, n; while (scanf("%d", &w) != EOF) { scanf("%d", &n); memset(dp, 0, sizeof(dp)); memset(f, false, sizeof(f)); for (int i = 1; i <= n; ++i) scanf("%d", &time[i]); for (int i = n; i >= 1; --i) for (int v = w; v >= time[i]; --v) if (dp[v] < dp[v-time[i]] + time[i]) dp[v] = dp[v-time[i]] + time[i], f[i][v] = true; for (int i = 1, j = w; i <= n; ++i) if (f[i][j]) printf("%d ", time[i]), j -= time[i]; printf("sum:%d\n", dp[w]); } return 0; }
-------------------------------------------------------
kedebug
Department of Computer Science and Engineering,
Shanghai Jiao Tong University
E-mail: kedebug0@gmail.com
GitHub: http://github.com/kedebug
-------------------------------------------------------