巡回セールスマン問題or-opt法について
Posted: 2013年6月05日(水) 17:00
巡回セールスマン問題をor-opt法のアルゴリズムを用いてとこうとしているのですが、振動してしまいうまくいきません。
コードは
void or_opt(void)
{
int temp,diff;
int i,j,k;
int t=0;
int i0,i1;
int j1;
length = 0;
for(i=0;i<n;i++){
length += Dis(tour,tour[i+1]);
}
or_opt:
for(i = t;i<t+n-1;i++){
for(j = i+2; j < t+n-2; j++){
i0 = i-1;
i1 = i+1;
if(i0 < 0) i0 = n-1;
if(i1 == n) i1=0;
for(j = i+2; j < t+n-2; j++){
j1 = j+1;
if(j1 == n) j1 = 0;
int ac = Dis(tour[i0 % n], tour[i1 % n]);
int cb = Dis(tour[i1 % n], tour[i % n]);
int ef = Dis(tour[j % n], tour[j1 % n]);
int ab = Dis(tour[i0 % n], tour[i % n]);
int ec = Dis(tour[j % n], tour[i1 % n]);
int cf = Dis(tour[i1 % n], tour[j1 % n]);
diff = (ac+cb+ef) - (ab+ec+cf);
if(diff < 0 && i!=j && i!=j1){
length = length - diff;
for(k = 0; k < (j-i)/2; k++){
temp = tour[(i+1+k) % n];
tour[(i+1+k) % n] = tour[(j-k) % n];
tour[(j-k) % n] = temp;
}
}else{
i++;
j++;
t++;
break;
}
t = i+1;
goto or_opt;
}
}
}
printf("After_or-opt_length=%d\n",length);
}
というふうに実装しています。
解答いただけるとありがたいです…
コードは
void or_opt(void)
{
int temp,diff;
int i,j,k;
int t=0;
int i0,i1;
int j1;
length = 0;
for(i=0;i<n;i++){
length += Dis(tour,tour[i+1]);
}
or_opt:
for(i = t;i<t+n-1;i++){
for(j = i+2; j < t+n-2; j++){
i0 = i-1;
i1 = i+1;
if(i0 < 0) i0 = n-1;
if(i1 == n) i1=0;
for(j = i+2; j < t+n-2; j++){
j1 = j+1;
if(j1 == n) j1 = 0;
int ac = Dis(tour[i0 % n], tour[i1 % n]);
int cb = Dis(tour[i1 % n], tour[i % n]);
int ef = Dis(tour[j % n], tour[j1 % n]);
int ab = Dis(tour[i0 % n], tour[i % n]);
int ec = Dis(tour[j % n], tour[i1 % n]);
int cf = Dis(tour[i1 % n], tour[j1 % n]);
diff = (ac+cb+ef) - (ab+ec+cf);
if(diff < 0 && i!=j && i!=j1){
length = length - diff;
for(k = 0; k < (j-i)/2; k++){
temp = tour[(i+1+k) % n];
tour[(i+1+k) % n] = tour[(j-k) % n];
tour[(j-k) % n] = temp;
}
}else{
i++;
j++;
t++;
break;
}
t = i+1;
goto or_opt;
}
}
}
printf("After_or-opt_length=%d\n",length);
}
というふうに実装しています。
解答いただけるとありがたいです…