标签:
01背包问题,并打印出路径
#include<iostream> #include<stdlib.h> using namespace std; #define MAX 100 int f[MAX][MAX]; int Path[MAX][MAX]; int main() { int Weight[] = {0,2,3,1,4,6,5}; int Value[] = {0,5,6,5,1,19,7}; int nCapacity = 10; //memset(f[0],-1,sizeof(f[0])); for(int i = 1;i<=6;i++) { for(int j=1;j<=nCapacity;j++) { if(j >= Weight[i] && f[i-1][j-Weight[i]]+Value[i] > f[i-1][j]) { f[i][j] = f[i-1][j-Weight[i]]+Value[i]; Path[i][j] = 1; } else f[i][j] = f[i-1][j]; cout<<f[i][j]<<" "; } cout<<endl; } int i=6,j=nCapacity; while(i>0 && j>0) { if(Path[i][j]==1) { cout<<Value[i]<<" "; j -= Weight[i]; } i--; } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u014338577/article/details/47340769