标签:
#include<iostream>#include<string>const int N=3; //物品个数const int W=50; //背包的容量struct Product{int value;int weight;};Product goods[N+1]={{0,0},{60,10},{100,20},{120,30}};//商品信息int select[N+1][W+1];int pktProb(){for(int w=1;w<W; w++){select[0][w]=0;}for(int i=1;i<=N; i++){select[i][0]=0; //背包容量为0时,最大价值为0,初使化for(int w=1; w<=W; w++){//考虑背包容量从1到W的子问题,在子问题的基础上求背包容量为W时的价值if(goods[i].weight<=w){//这里需要进行选择,只有当当前商品重量比包背的容量小时。if(select[i-1][w-goods[i].weight]+goods[i].value>select[i-1][w]){select[i][w]=goods[i].value+select[i-1][w-goods[i].weight];}else{select[i][w]=select[i-1][w];}}else{select[i][w]=select[i-1][w]; //则进行初使化}}}return select[N][W];}
for(int w=1;w<W; w++){ //这里做的目的是,我们考虑当商品数为0时,它的价值肯定是为0的。 select[0][w]=0;}
#include"oneZeroPackage.h"/*函数入口参数:pktVolum:背包的容量prtVolum:物品的体积prtValue: 物品的价值prtLen : 物品的个数测试代码:int prtValue[4]={0,6,10,12};int prtVolum[4]={0,1,2,3};std::cout<<oneZeropkt(5,prtVolum,prtValue,3)<<std::endl;*/int oneZeropkt(int pktVolum,int *prtVolum,int *prtValue,int prtLen){struct Goods *goods=new Goods[prtLen+1];int select[500][500];for(int i=1;i<=prtLen; i++){goods[i].value=prtValue[i];goods[i].volum=prtVolum[i];}for(int w=1;w<=pktVolum; w++){ //这个表示在背包有没有任何商品可选的情况下它的价值为0select[0][w]=0;}for(int i=1; i<=prtLen;i++){select[i][0]=0; //这个表示在背包的容量为0的情况下它的价值为0for(int w=1; w<=pktVolum;w++){if(w>=goods[i].volum){if(select[i-1][w-goods[i].volum]+goods[i].value>select[i-1][w]){select[i][w]=select[i-1][w-goods[i].volum]+goods[i].value;}else{select[i][w]=select[i-1][w];}}else{select[i][w]=select[i-1][w];}}}return select[prtLen][pktVolum];}
标签:
原文地址:http://www.cnblogs.com/yml435/p/4655570.html