IVl*_*lad 17 algorithm math optimization graph
我感兴趣的方法来改善或者想出了能够解决算法旅行商问题有关n = 100 to 200的城市.
我给出的维基百科链接列出了各种优化,但它在相当高的水平上这样做,我不知道如何在代码中实际实现它们.
工业有实力的求解器在那里,如协和,但这些办法,因为我想要的东西太复杂,而经典的解决方案,充斥搜索TSP所有在场的随机算法或经典的回溯或者动态规划算法,只有约工作20个城市.
那么,有没有人知道如何实现一个简单的(简单来说,我的意思是一个实现不需要超过100-200行代码)TSP求解器在至少100个城市的合理时间(几秒)内工作?我只对确切的解决方案感兴趣.
您可以假设输入将是随机生成的,因此我不关心专门用于破坏某种算法的输入.
com*_*les 51
200行和没有库是一个严格的约束.高级求解器使用Held-Karp松弛进行分支和绑定,我不确定即使是最基本的版本也能适应200条法线.不过,这是一个大纲.
将TSP编写为整数程序的一种方法如下(Dantzig,Fulkerson,Johnson).对于所有边e,常数w e表示边e的长度,如果边e在旅程中,则变量x e为1,否则为0.对于顶点的所有子集S,∂(S)表示连接S中的顶点与不在S中的顶点的边.
最小化和边缘Ë瓦特Ë X ë
受
1.所有顶点V,总和边缘E在∂({V}) X ë = 2
2.顶点的所有非空真子集S,总和边缘∂E(S) X ë ≥2
3.对于所有的边缘E在E,X ë在{0,1}
条件1确保边集是旅程的集合.条件2确保只有一个.(否则,让S为其中一个游览所访问的顶点集.)通过进行此更改来获得Held-Karp松弛.
3.对于所有的边缘E在E,X ë在{0,1}
3.于E所有边缘E,0≤X ë ≤1
Held-Karp是一个线性程序,但它具有指数数量的约束.解决它的一种方法是引入拉格朗日乘数,然后进行次梯度优化.归结为一个循环,它计算最小生成树,然后更新一些向量,但细节是涉及的.除了"Held-Karp"和"subgradient(descent | optimization)"之外,"1-tree"是另一个有用的搜索词.
(一个较慢的选择是写一个LP求解器并引入子层约束,因为它们被前一个optima所违反.这意味着编写一个LP求解器和一个min-cut过程,这也是更多的代码,但它可能更好地延伸到更具异国情调的TSP限制.)
通过"部分解决方案",我的意思是将变量部分分配给0或1,其中分配1的边缘肯定在巡回中,并且分配0的边缘肯定是out.使用这些侧面约束来评估Held-Karp可以在最佳巡视中给出一个下限,该巡视尊重已经做出的决策(扩展).
分支和边界维护一组部分解决方案,其中至少有一个扩展到最佳解决方案.一种变体的伪代码,具有最佳优先回溯的深度优先搜索如下.
let h be an empty minheap of partial solutions, ordered by Held–Karp value
let bestsolsofar = null
let cursol be the partial solution with no variables assigned
loop
while cursol is not a complete solution and cursol's H–K value is at least as good as the value of bestsolsofar
choose a branching variable v
let sol0 be cursol union {v -> 0}
let sol1 be cursol union {v -> 1}
evaluate sol0 and sol1
let cursol be the better of the two; put the other in h
end while
if cursol is better than bestsolsofar then
let bestsolsofar = cursol
delete all heap nodes worse than cursol
end if
if h is empty then stop; we've found the optimal solution
pop the minimum element of h and store it in cursol
end loop
Run Code Online (Sandbox Code Playgroud)
分支和绑定的想法是有一个部分解决方案的搜索树.解决Held-Karp的问题在于LP的值最多是最佳巡回的长度OPT,但也推测至少是3/4 OPT(实际上,通常更接近OPT).
我遗漏的伪代码中的一个细节是如何选择分支变量.目标通常是首先做出"硬"决策,因此修复一个值已接近0或1的变量可能并不明智.一种选择是选择最接近0.5,但有许多,其他许多.
Java实现.198个非空白,非注释行.我忘了单树不能将变量赋值给1,所以我通过找到一个树的度数> 2的顶点并依次删除每个边来进行分支.该程序接受TSPLIB实例的EUC_2D形式,例如,eil51.tsp与eil76.tsp和eil101.tsp和lin105.tsp从http://www2.iwr.uni-heidelberg.de/groups/comopt/software/TSPLIB95/tsp/.
// simple exact TSP solver based on branch-and-bound/Held--Karp
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class TSP {
// number of cities
private int n;
// city locations
private double[] x;
private double[] y;
// cost matrix
private double[][] cost;
// matrix of adjusted costs
private double[][] costWithPi;
Node bestNode = new Node();
public static void main(String[] args) throws IOException {
// read the input in TSPLIB format
// assume TYPE: TSP, EDGE_WEIGHT_TYPE: EUC_2D
// no error checking
TSP tsp = new TSP();
tsp.readInput(new InputStreamReader(System.in));
tsp.solve();
}
public void readInput(Reader r) throws IOException {
BufferedReader in = new BufferedReader(r);
Pattern specification = Pattern.compile("\\s*([A-Z_]+)\\s*(:\\s*([0-9]+))?\\s*");
Pattern data = Pattern.compile("\\s*([0-9]+)\\s+([-+.0-9Ee]+)\\s+([-+.0-9Ee]+)\\s*");
String line;
while ((line = in.readLine()) != null) {
Matcher m = specification.matcher(line);
if (!m.matches()) continue;
String keyword = m.group(1);
if (keyword.equals("DIMENSION")) {
n = Integer.parseInt(m.group(3));
cost = new double[n][n];
} else if (keyword.equals("NODE_COORD_SECTION")) {
x = new double[n];
y = new double[n];
for (int k = 0; k < n; k++) {
line = in.readLine();
m = data.matcher(line);
m.matches();
int i = Integer.parseInt(m.group(1)) - 1;
x[i] = Double.parseDouble(m.group(2));
y[i] = Double.parseDouble(m.group(3));
}
// TSPLIB distances are rounded to the nearest integer to avoid the sum of square roots problem
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
double dx = x[i] - x[j];
double dy = y[i] - y[j];
cost[i][j] = Math.rint(Math.sqrt(dx * dx + dy * dy));
}
}
}
}
}
public void solve() {
bestNode.lowerBound = Double.MAX_VALUE;
Node currentNode = new Node();
currentNode.excluded = new boolean[n][n];
costWithPi = new double[n][n];
computeHeldKarp(currentNode);
PriorityQueue<Node> pq = new PriorityQueue<Node>(11, new NodeComparator());
do {
do {
boolean isTour = true;
int i = -1;
for (int j = 0; j < n; j++) {
if (currentNode.degree[j] > 2 && (i < 0 || currentNode.degree[j] < currentNode.degree[i])) i = j;
}
if (i < 0) {
if (currentNode.lowerBound < bestNode.lowerBound) {
bestNode = currentNode;
System.err.printf("%.0f", bestNode.lowerBound);
}
break;
}
System.err.printf(".");
PriorityQueue<Node> children = new PriorityQueue<Node>(11, new NodeComparator());
children.add(exclude(currentNode, i, currentNode.parent[i]));
for (int j = 0; j < n; j++) {
if (currentNode.parent[j] == i) children.add(exclude(currentNode, i, j));
}
currentNode = children.poll();
pq.addAll(children);
} while (currentNode.lowerBound < bestNode.lowerBound);
System.err.printf("%n");
currentNode = pq.poll();
} while (currentNode != null && currentNode.lowerBound < bestNode.lowerBound);
// output suitable for gnuplot
// set style data vector
System.out.printf("# %.0f%n", bestNode.lowerBound);
int j = 0;
do {
int i = bestNode.parent[j];
System.out.printf("%f\t%f\t%f\t%f%n", x[j], y[j], x[i] - x[j], y[i] - y[j]);
j = i;
} while (j != 0);
}
private Node exclude(Node node, int i, int j) {
Node child = new Node();
child.excluded = node.excluded.clone();
child.excluded[i] = node.excluded[i].clone();
child.excluded[j] = node.excluded[j].clone();
child.excluded[i][j] = true;
child.excluded[j][i] = true;
computeHeldKarp(child);
return child;
}
private void computeHeldKarp(Node node) {
node.pi = new double[n];
node.lowerBound = Double.MIN_VALUE;
node.degree = new int[n];
node.parent = new int[n];
double lambda = 0.1;
while (lambda > 1e-06) {
double previousLowerBound = node.lowerBound;
computeOneTree(node);
if (!(node.lowerBound < bestNode.lowerBound)) return;
if (!(node.lowerBound < previousLowerBound)) lambda *= 0.9;
int denom = 0;
for (int i = 1; i < n; i++) {
int d = node.degree[i] - 2;
denom += d * d;
}
if (denom == 0) return;
double t = lambda * node.lowerBound / denom;
for (int i = 1; i < n; i++) node.pi[i] += t * (node.degree[i] - 2);
}
}
private void computeOneTree(Node node) {
// compute adjusted costs
node.lowerBound = 0.0;
Arrays.fill(node.degree, 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) costWithPi[i][j] = node.excluded[i][j] ? Double.MAX_VALUE : cost[i][j] + node.pi[i] + node.pi[j];
}
int firstNeighbor;
int secondNeighbor;
// find the two cheapest edges from 0
if (costWithPi[0][2] < costWithPi[0][1]) {
firstNeighbor = 2;
secondNeighbor = 1;
} else {
firstNeighbor = 1;
secondNeighbor = 2;
}
for (int j = 3; j < n; j++) {
if (costWithPi[0][j] < costWithPi[0][secondNeighbor]) {
if (costWithPi[0][j] < costWithPi[0][firstNeighbor]) {
secondNeighbor = firstNeighbor;
firstNeighbor = j;
} else {
secondNeighbor = j;
}
}
}
addEdge(node, 0, firstNeighbor);
Arrays.fill(node.parent, firstNeighbor);
node.parent[firstNeighbor] = 0;
// compute the minimum spanning tree on nodes 1..n-1
double[] minCost = costWithPi[firstNeighbor].clone();
for (int k = 2; k < n; k++) {
int i;
for (i = 1; i < n; i++) {
if (node.degree[i] == 0) break;
}
for (int j = i + 1; j < n; j++) {
if (node.degree[j] == 0 && minCost[j] < minCost[i]) i = j;
}
addEdge(node, node.parent[i], i);
for (int j = 1; j < n; j++) {
if (node.degree[j] == 0 && costWithPi[i][j] < minCost[j]) {
minCost[j] = costWithPi[i][j];
node.parent[j] = i;
}
}
}
addEdge(node, 0, secondNeighbor);
node.parent[0] = secondNeighbor;
node.lowerBound = Math.rint(node.lowerBound);
}
private void addEdge(Node node, int i, int j) {
double q = node.lowerBound;
node.lowerBound += costWithPi[i][j];
node.degree[i]++;
node.degree[j]++;
}
}
class Node {
public boolean[][] excluded;
// Held--Karp solution
public double[] pi;
public double lowerBound;
public int[] degree;
public int[] parent;
}
class NodeComparator implements Comparator<Node> {
public int compare(Node a, Node b) {
return Double.compare(a.lowerBound, b.lowerBound);
}
}
Run Code Online (Sandbox Code Playgroud)