01背包路径输出
来源:互联网 发布:java学生管理系统 编辑:程序博客网 时间:2024/06/06 10:05
确实很少遇到要求输出背包路径的题,今天无聊整理了两种方法:
code:(1)
#include<iostream>#include<cstdio>#include<cstring>using namespace std;int dp[10005];bool path[105][10005];int c[10005],w[10005];int main(){ int N,V; while (cin>>V>>N) { memset(path,0,sizeof(path)); memset(dp,0,sizeof(dp)); for (int i = 1;i <= N;++i) cin>>c[i]>>w[i]; for (int i = N;i >= 1;--i) { for (int j = V;j >= c[i];--j) { if (dp[j] < dp[j-c[i]]+w[i]) { dp[j] = dp[j-c[i]]+w[i]; path[i][j] = 1;} } } cout<<dp[V]<<endl; puts("-----------------------------------------"); for (int i = 1,j = V;i <= N&&j > 0;i++) { if (path[i][j]) { printf("%d ",i); j -= c[i];} } puts(""); } return 0;}/*70 371 10069 11 270 369 11 271 1001000 5800 1600400 2000300 1500400 1200200 40010 35 55 48 23 31 11 11 1*/
code:(2)
#include <iostream>#include <string>#include <cstring>#define INF 0x3f3f3f3f#define MAXN 100005using namespace std;int n,V;struct Node{ int v; string path; void Init() { string init(n,'0'); v = 0; path = init;}}dp[MAXN];int val[MAXN];int vol[MAXN];int main(){ while(cin>>n>>V) { for(int i=1;i<=n;i++) cin>>vol[i]>>val[i]; for(int i=0;i<=V;i++) { dp[i].Init(); } for(int i=1;i<=n;i++) { for(int j=V;j>=vol[i];j--) { if(dp[j].v<dp[j-vol[i]].v+val[i]) { dp[j].v=dp[j-vol[i]].v+val[i]; dp[j].path=dp[j-vol[i]].path; dp[j].path[i-1]='1'; } }} cout<<dp[V].v<<endl; cout<<dp[V].path<<endl; } return 0;}/*5 1000800 1600400 2000300 1500400 1200200 4003 105 55 48 23 31 11 11 1*/
0 0
- 01背包路径输出
- UVa 624 CD (01背包路径输出)
- uva624 CD 01背包+输出路径
- UVA 264 CD (01背包+输出路径)
- 背包输出路径
- UVA 624 —— 01背包&路径输出
- Happy Programming Contest ZOJ+01背包问题+路径输出
- uva624 CD (01背包+路径的输出)
- UVA 题目624 CD(01背包输出路径啊)
- Hrbust 1836 2012世界末日【01背包+反路径输出】
- CF864E:E. Fire(01背包 & 路径输出)
- Codeforces Round #436 E.Fire(01背包 + 输出路径)
- POJ1787 【完全背包+物品计数+路径输出】
- 01背包+记录路径
- 01背包查找路径
- hrbust/哈理工oj 1740 A Story on a Sunshine Beach【二维01背包+输出路径】
- Codeforces Round #436 (Div. 2)-E-Fire(01背包输出路径)
- Codeforces Round #436 (Div. 2) E. Fire(01背包+输出路径)
- Elasticsearch - 短语匹配(match_phrase)以及slop参数
- java io(一)
- [IOS]Label-UIMenuController
- 21. Merge Two Sorted Lists | Java最短代码实现
- windows客户端开发--为你的客户端增加日志系统(log4cplus)
- 01背包路径输出
- PHP设计模式之适配器模式
- 结构体练手
- 设置Linux系统的时区
- 巧用setContentView的应用
- 关于strcpy函数的实现
- 打开Linux ftp服务,如:vsftpd: unrecognized service
- 冒泡排序
- android自定义滑动选择开关