您的位置:首页 > 其它

01背包路径输出

2016-04-07 23:56 288 查看
确实很少遇到要求输出背包路径的题,今天无聊整理了两种方法:

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

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: