赞
踩
背包问题要求从 n 个物品中选取若干装入一个背包中。每个物品有体积(vi>0)和价值(pi),每个箱子有体积限制()。目标是寻找最优的将物品分配到背包的方案,使每个背包中物品的体积之和不超过容积限制,而价值最大。
(1)
(2)
式中,xi=1表示物品i被装入箱子,xi=0则表示物品i未被选中。
从下面物品中选取若干,在总体积不超过1000情况下使总价值最大。
序号 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
体积 | 80 | 82 | 85 | 70 | 72 | 70 | 66 | 50 | 55 | 25 |
价值 | 220 | 208 | 198 | 192 | 180 | 180 | 165 | 162 | 160 | 158 |
序号 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 |
体积 | 50 | 55 | 40 | 48 | 50 | 32 | 22 | 60 | 30 | 32 |
价值 | 155 | 130 | 125 | 122 | 120 | 118 | 115 | 110 | 105 | 101 |
序号 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |
体积 | 40 | 38 | 35 | 32 | 25 | 28 | 30 | 22 | 50 | 30 |
价值 | 100 | 100 | 98 | 96 | 95 | 90 | 88 | 82 | 80 | 77 |
序号 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 |
体积 | 45 | 30 | 60 | 50 | 20 | 65 | 20 | 25 | 30 | 10 |
价值 | 75 | 73 | 72 | 70 | 69 | 66 | 65 | 63 | 60 | 58 |
序号 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 |
体积 | 20 | 25 | 15 | 10 | 10 | 10 | 4 | 4 | 2 | 1 |
价值 | 56 | 50 | 30 | 20 | 15 | 10 | 8 | 5 | 3 | 1 |
遗传编码考虑为长度为50,表示某个物品是否被选中,变异交叉可正常进行。
- %v=profit
- v=xlsread('H:\original\profit_and_weight.xlsx','sheet1','A1:A50');
- V0=1500;
- %种群大小
- popsize=4;
- %二进制编码长度
- chromlength=50;
- %交叉概率
- pc = 0.3;
- %变异概率
- pm = 0.001;
- %初始种群
- pop = initpop(popsize,chromlength);
- hanshuzhi=zeros(100,1);
- % [bestindividual,bestfit] = best(pop,fitvalue);
- % hanshuzhi(1)=bestfit;
- for i = 1:100
- %计算适应度值(函数值)
- [objvalue,newpop1] = cal_objvalue(pop,V0,v);
- fitvalue = objvalue;
- %选择操作
- newpop = selection(newpop1,fitvalue);
- %交叉操作
- newpop = crossover(newpop,pc);
- %变异操作
- newpop = mutation(newpop,pm);
- %寻找最优解
- [bestindividual,bestfit] = best(pop,fitvalue);
- hanshuzhi(i)=bestfit;
- %更新种群
- t=1;
- for j=1:popsize
- if fitvalue(j)==bestfit
- newpop(t)=pop(j);
- t=t+1;
- end
- end
- pop = newpop;
-
-
- if i==100
- number=1:50;
- lastindividual=number(bestindividual==1);
- end
- end
- extra_space=ones(100,1);
- for i=1:100
- extra_space(i)=V0-hanshuzhi(i);
- end
- fprintf('The best individual is --->>%2f\n');
- lastindividual
- fprintf('The best value is --->>%5.2f\n',min(extra_space));
- figure
- plot(extra_space(:),'k');
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。