/*
* 01背包问题
* 但是要注意输出的问题
* 状态转移的时候记录当前状态的当前值是否已选
* 最后递归输出结果
*/
/ *
* 01 knapsack problem
* However, to pay attention to the problem of the output
* Record the current state of the current value of the state transition is selected
* Last recursive output
* /
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAXN 10000
#define MAXM 25
int dp[MAXN], val[MAXN], pre[MAXM][MAXN];
void back_trace(int v, int cnt)
{
if( !cnt ) {
return ;
}
if( pre[cnt][v] ) {
back_trace(v-val[cnt], cnt-1);
printf("%d ", val[cnt]);
}
else {
back_trace(v, cnt-1);
}
}
void zero_one_package(int max_v, int n)
{
memset(dp, 0, sizeof(dp));
memset(pre, 0, sizeof(pre));
for(int i = 1; i <= n; i ++) {
scanf("%d", &val[i]);
for(int v = max_v; v >= val[i]; v --) {
if( dp[v] <= dp[v-val[i]]+val[i] ) {
dp[v] = dp[v-val[i]]+val[i];
pre[i][v] = 1;
}
}
}
back_trace(max_v, n);
printf("sum:%d\n", dp[max_v]);
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
int v, n;
while( ~scanf("%d %d", &v, &n) ) {
zero_one_package(v, n);
}
return 0;
}
uva_624
最新推荐文章于 2019-07-19 14:17:02 发布