状态转移方程 B[n][w]=B[n-1][w-W[i]]+V[i] 表示取走第n个物品,重量为W时的价值量。 W V分别存放重量和价值的数组。#include<iostream>
#include<vector>
#include<math.h>
// 背包问题
using namespace std;
int value[]={3,4,5,8,10};
int weight[]={2,3,4,5,9};
const int N=5;
const int W=20;
int B[N+1][W+1];
int main()
{
for(int i=1;i<=N;++i)
{
for(int k=1;k<=W;++k)
{
if(weight[i-1]>k)
{
B[i][k]=B[i-1][k];
}
else
{
B[i][k]=max(B[i-1][k],B[i-1][k-weight[i-1]]+value[i-1]);
}
}
}
cout<<B[N][W];
return 0;
}