我正在尝试将旅行商问题的2-opt实施转换为3-opt。据我所知,与2-opt相比,删除3个边缘并将其替换为希望获得更好的距离。我有问题找出改变/添加到我的2-opt交换的内容,使其成为三个选择。我遇到的主要问题是如何确保在单个交换函数中考虑所有8种交换。 谢谢
2-opt代码:
private static int[] TwoOpt(int[] TSP) {
double best = totalDistance;
int numCities = TSP.length;
int visited = 0;
int current = 0;
int[] newTour = TSP;
while (visited < numCities) {
for (int i = 0; i < numCities - 1; i++) {
for (int j = i + 1; j < numCities; j++) {
int[] newerTour = Swap(i, j, newTour);
int newDistance = distance(newerTour);
if (newDistance < best) {
visited = 0;
best = newDistance;
newTour = newerTour;
}
}
}
visited++;
}
return newTour;
}
private static int distance(int[] newTour) {
int distance = 0;
for (int i = 0; i < newTour.length - 1; i++) {
distance += mstList.get(i).get(i + 1).p;
}
distance += mstList.get(newTour.length).get(0).p;
return distance;
}
private static int[] Swap(int i, int j, int[] tour) {
int size = tour.length;
int[] newerTour = new int[tour.length];
for (int c = 0; c <= i - 1; c++) {
newerTour[c] = tour[c];
}
int change = 0;
for (int d = i; d <= j; d++) {
newerTour[d] = tour[d - change];
change++;
}
for (int e = j + 1; e < size; e++) {
newerTour[e] = tour[e];
}
return newerTour;
}
这就是我对三选的实现,没有实现交换。
private static int[] ThreeOpt(int[] TSP) {
double best = totalDistance;
int numCities = TSP.length;
int visited = 0;
int current = 0;
int[] newTour = TSP;
while (visited < numCities) {
for (int i = 0; i < numCities - 2; i++) {
for (int j = i + 1; j < numCities - 1; j++) {
for (int k = j + 1; k < numCities; k++) {
int[] newerTour = Swap(i, j, k, newTour);
int newDistance = distance(newTour);
if (newDistance < best) {
visited = 0;
best = newDistance;
newTour = newerTour;
}
}
}
}
visited++;
}
return newTour;
}
答案 0 :(得分:0)
实际上只有4种形式的3-opt。
将巡回演变为3部分A->,B-&gt;,C-&gt;
将B连接到A和C的两条边上的2-opt是:
即。只是扭转B的旅程。
现在为3-opt
注意A->,&lt; -B,C-&gt;和A->,B->,&lt; -C和A->,&lt; -C,&lt; -B都是2-opt。
逆转很容易实现,你只需要考虑4个变量。