思路厘清后,开始编程序,C语言代码如下所示。
#include
int c[10][100]={0};
void knap(int m,int n){
int i,j,w[10],p[10];
for(i=1;ic[i-1][j])
c[i][j]=c[i-1][j-w[i]]+p[i];
else
c[i][j]=c[i-1][j];
}
}
int main(){
int m,n;int i,j;
printf("input the max capacity and the number of the goods:\n");
scanf("%d,%d",&m,&n);
printf("Input each one(weight and value):\n");
knap(m,n);
printf("\n");
for(i=0;i<=n;i++)
for(j=0;j<=m;j++)
{
printf("%4d",c[i][j]);
if(m==j) printf("\n");
}
}
代码中,红色字体部分是自己写的,其余的参照了这篇博客http://blog.sina.com.cn/s/blog_6dcd26b301013810.html
自顶向下
#include
#include
#include
#include "iostream"
using namespace std;
const int N = 4;
const int W = 5;
int weight[N] = {2, 1, 3, 2};
int value[N] = {3, 2, 4, 2};
int record[N][W];
void init()
{
for(int i = 0; i < N; i ++)
{
for(int j = 0; j < W; j ++)
{
record[i][j] = -1;
}
}
}
int solve(int i, int residue)
{
if(-1 != record[i][residue])
return record[i][residue];
int result = 0;
if(i >= N)
return result;
if(weight[i] > residue)
{
record[i + 1][residue] = solve(i+1, residue);
}
else
{
result = max(solve(i+1, residue), solve(i+1, residue-weight[i]) + value[i]);
}
return record[i + 1][residue] = result;
}
int main() {
init();
int result = solve(0, W);
cout << result << endl;
return 0;
}