01背包路径输出
2016-04-07 23:56
288 查看
确实很少遇到要求输出背包路径的题,今天无聊整理了两种方法:
code:(1)
code:(2)
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 3 71 100 69 1 1 2 70 3 69 1 1 2 71 100 1000 5 800 1600 400 2000 300 1500 400 1200 200 400 10 3 5 5 5 4 8 2 3 3 1 1 1 1 1 1 */
code:(2)
#include <iostream> #include <string> #include <cstring> #define INF 0x3f3f3f3f #define MAXN 100005 using 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 1000 800 1600 400 2000 300 1500 400 1200 200 400 3 10 5 5 5 4 8 2 3 3 1 1 1 1 1 1 */
相关文章推荐
- Google Test(GTest)使用方法和源码解析——预处理技术分析和应用
- windows客户端开发--为你的客户端增加日志系统(log4cplus)
- php常用的排序算法与二分法查找
- hdu-1542 Atlantis(离散化+线段树+扫描线算法)
- azure blobs
- [IOS]Label-UIMenuController
- Google Test(GTest)使用方法和源码解析——断言的使用方法和解析
- Google Test(GTest)使用方法和源码解析——Listener技术分析和应用
- 分布式服务框架 dubbo/dubbox 入门示例
- java io(一)
- 数组I冒泡法排序
- IOS学习笔记——UIView家族
- Google Test(GTest)使用方法和源码解析——结果统计机制分析
- SQL Server ->> T-SQL查询面试题之实例版
- python获取绑定的IP,并动态指定出口IP
- bug_ _小心android-support-v4.jar版本混乱造成的NoClassDefFoundError
- 使用异步任务下载--疯狂android讲义实例
- android最佳实践指南
- ON_MESSAGE
- 周总结