01背包问题(动态规划求解)
01背包的状态转换方程 f[i,j] = Max{ f[i-1,j-Wi]+Pi( j >= Wi ), f[i-1,j] }
Wi为第i件物品的重量,Pi为第i件物品的价值。
测试数据:重量4,价值6;重量5,价值4;重量6,价值5;重量2,价值3;重量2,价值6;背包总重量限制为10
代码:
#include<iostream> using namespace std; #define MAX 100//define the max row and colum int arr[MAX][MAX]={0};//initial the arrary void cacl(int vlae[],int weight[],int tweight,int N)//cacl { int i,j; int t; for(i=0;i<N;i++) { for(j=0;j<tweight;j++) { t=i+1; if(j<weight[i]-1) { arr[t][j]=arr[t-1][j]; } else { if(arr[t-1][j-weight[i]]+vlae[i]>arr[t-1][j]) arr[t][j]=arr[t-1][j-weight[i]]+vlae[i]; else arr[t][j]=arr[t-1][j]; } cout<<arr[t][j]<<" "; } cout<<endl; } cout<<"The largest vale of the backpack is:"<<arr[t][j-1]<<endl; } int main() { int weight[MAX]={0};//背包重量 int vale[MAX]={0}; int N,tweight; cout<<"Input the total weight:"; cin>>tweight; cout<<"Input the total data number:"; cin>>N; for(int i=0;i<N;i++) { cin>>weight[i]; cin>>vale[i]; } cacl(vale,weight,tweight,N);//计算最优解 return 0; }
测试结果: