a = 0.95;
weight = [2;5;18;3;2;5;10;4;11;7;14;6];
value = [5;10;13;4;3;11;13;10;8;16;7;4];
value = -value;
restriction = 46;
num = 12;
newSol = ones(1,num);
curValue = inf; bestValue = inf;
curSol = newSol; bestSol =newSol;
T0 = 97; Tf = 3; t = T0;
p = 1;
while t >= Tf
for r = 1:100
%产生随机扰动
tmp = ceil(rand*num);
newSol(1, tmp) =~newSol(1, tmp);
%检查是否满足约束条件
while 1
q = (newSol*weight <= restriction);
if q
break;
else
p = ~p;
tmp1 = find(newSol == 1);
if p
newSol(1, tmp1) = 0;
else
newSol(1, tmp1(end)) = 0;
end
end
end
newValue = newSol*value;
if newValue < curValue
curValue = newValue;
curSol = newSol;
if newValue < bestValue
bestValue = newValue;
bestSol = newSol;
end
else
if rand < exp(-(newValue-curValue)/t)
curValue = newValue;
curSol = newSol;
else
newSol = curSol;
end
end
end
t = t*a;
end
disp('最优解为:');
disp(bestSol);
disp('背包中物品总价值为:');
bestValue = -bestValue;
disp(bestValue);
disp('背包中物品总重量为:');
disp(bestSol*weight);
《模拟退火(SA)求解0-1背包问题》
猜你喜欢
转载自blog.csdn.net/wuchangi/article/details/79176101
今日推荐
周排行