贪心算法经常与其他智能算法结合,形成改进的优化算法,加入贪心算法可以生成一个较优的初始解,也能对解进行改进。这篇小文章是用贪心算法修复背包问题的解。
直接上代码
W=[95 4 60 32 23 72 80 62 65 46];%物品重量
P=[55 10 47 5 4 50 8 61 85 87];%物品价值
V=269;%背包最大容量
n=size(W,2);%物品个数
M=30;%萤火虫种群个数
xn=round(rand(M,n));%随机生成初始解
%%
%对当前解用改进贪心算法修复,使不可行解变为可行解,并使可行解尽量增加其价值
function [xn]=f_GA(xn,M,n,V,P,W)
[fn,index]=sort(P./W,'ascend');
coresV=sum((W.*xn)');%当前背包重量
for i=1:M
if coresV(i)>V
for j=1:n
if xn(i,index(j))==1
coresV(i)=coresV(i)-W(index(j));
if coresV(i)>V
xn(i,index(j)) = 0;
else
xn(i,index(j)) = 0;
break
end
end
end
end
rest=[];index2=[];
for k=1:n
if xn(i,index(k))==0
rest(end+1)=fn(index(k));
index2(end+1)=index(k);
end
end
rest=fliplr(rest);index2=fliplr(index2);
for j=1:size(rest,2)
coresV(i)=coresV(i)+W(index2(j));
if coresV(i)
xn(i,index2(j))=1;
continue
else
coresV(i)=coresV(i)-W(index2(j));
end
end
end
end
以上代码结合了萤火虫算法的内容,但不影响贪心算法的实现,它不只是在对一个解进行修复,而是在对一群解进行修复。
参考文献:任静敏,潘大志《带权重的贪心萤火虫算法求解0-1背包问题》
未经允许,禁止转载