01背包路径输出

确实很少遇到要求输出背包路径的题,今天无聊整理了两种方法:

code:(1)

#include
#include
#include
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< 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 
#include 
#include 
#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



你可能感兴趣的:(ACM题解与算法,ACM(算法))