uva_624_CD
来源:互联网 发布:linux ssh远程登录命令 编辑:程序博客网 时间:2024/04/28 02:30
裸的背包题目+路径回溯#include <cstdio>#include <cstring>#include <algorithm>using namespace std;#define MAXN 21#define MAXV 10001int v[MAXN], dp[MAXV], pre[MAXN][MAXV];void back_track(const int &idx, const int &cur_v){ for(int i = idx-1; i >= 1; i --) { if( 1 == pre[i][ cur_v-v[idx] ] ) { back_track(i, cur_v-v[idx]); break; } } printf("%d ", v[idx]);}void dynamic_programming(const int &n, const int &max_v){ memset(pre, -1, sizeof(pre)); memset(dp, 0, sizeof(dp)); dp[0] = 1; for(int i = 1; i <= n; i ++) { for(int j = max_v; j >= v[i]; j --) { if( dp[ j-v[i] ] ) { dp[j] = pre[i][j] = 1; } } } for(int i = max_v; i >= 0; i --) { if( !dp[i] ) { continue; } for(int j = n; j >= 1; j --) { if( 1 == pre[j][i] ) { back_track(j, i); printf("sum:%d\n", i); return; } } }}int main(int argc, char const *argv[]){#ifndef ONLINE_JUDGE freopen("test.in", "r", stdin);#endif int max_v, n; while( ~scanf("%d %d", &max_v, &n) ) { for(int i = 1; i <= n; i ++) { scanf("%d", &v[i]); } dynamic_programming(n, max_v); } return 0;}