数学建模常用Matlab/Lingo/c代码总结系列——旅行商TSP问题

Lingo代码:
MODEL: 

  SETS: 
  CITY / 1.. 6/: U; ! U( I) = sequence no. of city; 
  LINK( CITY, CITY): 
       DIST,  ! The distance matrix; 
          X;  ! X( I, J) = 1 if we use link I, J; 
 ENDSETS 
 DATA:   !Distance matrix, it need not be symmetric; 
  DIST =0 56 35 21 51 60 
 	56 0 21 57 78 70 
 	35 21 0 36 68 68 
 	21 57 36 0 51 61 
 	51 78 68 51 0 13 
 	60 70 68 61 13 0; 
 ENDDATA 
 !The model:Ref. Desrochers & Laporte, OR Letters, 
  Feb. 91; 
  N = @SIZE( CITY); 
  MIN = @SUM( LINK: DIST * X); 
  @FOR( CITY( K): 
  !  It must be entered; 
   @SUM( CITY( I)| I #NE# K: X( I, K)) = 1; 
  !  It must be departed; 
   @SUM( CITY( J)| J #NE# K: X( K, J)) = 1; 
  ! Weak form of the subtour breaking constraints; 
  ! These are not very powerful for large problems; 
   @FOR( CITY( J)| J #GT# 1 #AND# J #NE# K: 
       U( J) >= U( K) + X ( K, J) - 
       ( N - 2) * ( 1 - X( K, J)) + 
       ( N - 3) * X( J, K))); 
  ! Make the X's 0/1; 
  @FOR( LINK: @BIN( X)); 
  ! For the first and last stop we know...; 
  @FOR( CITY( K)| K #GT# 1: 
   U( K) <= N - 1 - ( N - 2) * X( 1, K); 
   U( K) >= 1  + ( N - 2) * X( K, 1)); 
END 
 
matlab代码:

function main 
clc,clear 
global a 
% a=zeros(6); 
% a(1,2)=56;a(1,3)=35;a(1,4)=21;a(1,5)=51;a(1,6)=60; 
% a(2,3)=21;a(2,4)=57;a(2,5)=78;a(2,6)=70; 
% a(3,4)=36;a(3,5)=68;a(3,6)=68; a(4,5)=51;a(4,6)=61; 
% a(5,6)=13; a=a+a'; 
load cost
a=Muti_Cost;%边权矩阵
L=size(a,1); 
c1=1:53; %初始圈
[circle,long]=modifycircle(c1,L); 
c2=[1 53 2:52];%改变初始圈,该算法的最后一个顶点不动 
[circle2,long2]=modifycircle(c2,L); 
if long2<long 
   long=long2; 
   circle=circle2; 
end 
circle,long 
%******************************************* 
%修改圈的子函数 
%******************************************* 
function [circle,long]=modifycircle(c1,L); 
global a 
flag=1; 
while flag>0 
      flag=0; 
   for m=1:L-3 
      for n=m+2:L-1 
        if a(c1(m),c1(n))+a(c1(m+1),c1(n+1))<... 
           a(c1(m),c1(m+1))+a(c1(n),c1(n+1)) 
           flag=1; 
           c1(m+1:n)=c1(n:-1:m+1); 
        end 
     end 
  end 
end 
long=a(c1(1),c1(L)); 
for i=1:L-1 
   long=long+a(c1(i),c1(i+1)); 
end 
circle=c1; 



你可能感兴趣的:(c,function,matlab,constraints,Matrix,distance)