背包问题,代码有误,仅供本人参考
#include "stdafx.h"
#include<iostream>using namespace std;
int max(int a,int b)
{
return a>b?a:b;
}
int KnapSnack(int capacity,int n,int weight[],int value[])
{
int i;
int totalvalue[100]={0};
for(i=0;i<n;i++)
{
while(capacity>=0)
{
totalvalue[capacity]=max(totalvalue[capacity],totalvalue[capacity-weight[i]]+value[i]);
capacity= capacity-weight[i];
}
}
return totalvalue[capacity];
}
int _tmain(int argc, _TCHAR* argv[])
{
int weight[10]={4,5,6,3,2,7,8,9,10,11};
int value[10]={5,6,2,3,1,4,8,7,5,6};
int totalvalue=KnapSnack(30,10,weight,value);
cout<<totalvalue<<endl;
return 0;
}