TExcelTAD
Home › Approximation Algorithms › Metric TSP and the Double-Tree Algorithm

Metric TSP and the Double-Tree Algorithm

The travelling salesman problem asks for a shortest cycle through all nn vertices of a complete graph with edge costs c(u,v)≥0c(u, v) \ge 0. Without restrictions on the costs it cannot be approximated within any factor unless P = NP (Gap-Introducing Reductions has the proof). With the triangle inequality c(u,w)≤c(u,v)+c(v,w)c(u, w) \le c(u, v) + c(v, w), constant factors become possible. This lesson studies the simplest one, the double-tree algorithm, in the language of Euler tours that Christofides' algorithm will reuse, and builds an instance on which it really loses a factor 2.

Where metric costs come from

Costs are metric whenever they are shortest-path distances: road networks, travel times, distances in the plane. If a salesperson may pass through a city more than once, any cost function can be replaced by its metric closure, cˉ(u,v)\bar c(u, v) = the length of a shortest uu-vv path, and a tour for cˉ\bar c turns back into a closed walk of the same cost for cc. So "TSP where revisits are allowed" and "metric TSP" are the same problem.

Eulerian multigraphs and shortcutting

A connected multigraph has an Euler circuit, a closed walk using every edge exactly once, if and only if every vertex has even degree (Euler, 1736; Hierholzer's algorithm finds it in linear time). Under the triangle inequality, an Euler circuit that visits every vertex can be turned into a tour that is no longer:

Lemma (shortcutting). Let WW be a closed walk visiting every vertex. Listing the vertices in the order of their first visit and returning to the start gives a tour TT with c(T)≤c(W)c(T) \le c(W).

Proof. Each tour edge (u,w)(u, w) replaces a stretch u,v1,…,vr,wu, v_1, \ldots, v_r, w of WW, and repeated triangle inequalities give c(u,w)≤c(u,v1)+⋯+c(vr,w)c(u, w) \le c(u, v_1) + \cdots + c(v_r, w). Summing over the tour edges, c(T)≤c(W)c(T) \le c(W). □\square

So a cheap connected Eulerian spanning multigraph gives a cheap tour. The double-tree algorithm builds one in the most direct way.

text
DOUBLE-TREE(G, c)
1  T = a minimum spanning tree of G
2  D = T with every edge doubled          -- every degree is now even
3  W = an Euler circuit of D
4  return the tour obtained by shortcutting W

Theorem. For metric costs, the double-tree algorithm is a 2-approximation.

Proof. Removing an edge from an optimal tour leaves a spanning path, a spanning tree, so c(T)≤OPTc(T) \le \text{OPT}. The Euler circuit uses every edge of DD once: c(W)=2c(T)c(W) = 2c(T). Shortcutting does not increase the cost: ALG≤2c(T)≤2 OPT\text{ALG} \le 2c(T) \le 2\,\text{OPT}. □\square

Step 1 is the practice problem Minimum Spanning Tree. Walking an Euler circuit of the doubled tree and shortcutting is the same as listing the vertices in depth-first preorder, which is the formulation in Coping with NP-Hardness. The program builds the Euler circuit explicitly with Hierholzer's algorithm and compares the result with the exact optimum (Held-Karp dynamic programming).

python · try it yourself
import random
from math import dist, inf

def mst(pts):
    n = len(pts)
    best, parent, done, edges = [inf] * n, [-1] * n, [False] * n, []
    best[0] = 0
    for _ in range(n):
        u = min((i for i in range(n) if not done[i]), key=lambda i: best[i])
        done[u] = True
        if parent[u] >= 0:
            edges.append((parent[u], u))
        for v in range(n):
            if not done[v] and dist(pts[u], pts[v]) < best[v]:
                best[v], parent[v] = dist(pts[u], pts[v]), u
    return edges

def euler_circuit(n, multiedges):
    adj = {v: [] for v in range(n)}
    for i, (u, v) in enumerate(multiedges):
        adj[u].append((v, i))
        adj[v].append((u, i))
    used, stack, circuit = [False] * len(multiedges), [0], []
    while stack:                                   # Hierholzer
        u = stack[-1]
        while adj[u] and used[adj[u][-1][1]]:
            adj[u].pop()
        if adj[u]:
            v, i = adj[u].pop()
            used[i] = True
            stack.append(v)
        else:
            circuit.append(stack.pop())
    return circuit

def shortcut(walk):
    seen, tour = set(), []
    for v in walk:
        if v not in seen:
            seen.add(v)
            tour.append(v)
    return tour

def held_karp(pts):
    n = len(pts)
    D = [[inf] * n for _ in range(1 << n)]
    D[1][0] = 0.0
    for S in range(1, 1 << n, 2):
        for j in range(n):
            if D[S][j] < inf:
                for k in range(1, n):
                    if not S >> k & 1:
                        D[S | 1 << k][k] = min(D[S | 1 << k][k], D[S][j] + dist(pts[j], pts[k]))
    return min(D[-1][j] + dist(pts[j], pts[0]) for j in range(1, n))

length = lambda pts, t: sum(dist(pts[t[i]], pts[t[i - 1]]) for i in range(len(t)))
rng = random.Random(8)
print(" n    MST   walk   tour    OPT  tour/OPT")
for n in [7, 8, 9, 10]:
    pts = [(rng.randint(0, 100), rng.randint(0, 100)) for _ in range(n)]
    T = mst(pts)
    W = euler_circuit(n, T + T)
    tour = shortcut(W)
    c_T = sum(dist(pts[u], pts[v]) for u, v in T)
    opt = held_karp(pts)
    print(f"{n:2} {c_T:6.1f} {length(pts, W):6.1f} {length(pts, tour):6.1f} {opt:6.1f} {length(pts, tour) / opt:8.3f}")
 n    MST   walk   tour    OPT  tour/OPT
 7  167.0  334.0  235.4  235.4    1.000
 8  173.8  347.6  267.2  262.2    1.019
 9  175.4  350.7  305.5  257.7    1.185
10  176.1  352.2  286.7  268.6    1.067

Each row shows the chain MST≤OPT≤tour≤walk=2 MST\text{MST} \le \text{OPT} \le \text{tour} \le \text{walk} = 2\,\text{MST}.

In C++

Prim's algorithm on a cost matrix, then the preorder of the tree, which is the shortcut Euler circuit.

cpp · try it yourself
#include <cmath>
#include <cstdio>
#include <functional>
#include <vector>

int main() {
    std::vector<std::pair<double, double>> p = {{10, 80}, {30, 20}, {55, 65}, {90, 15}, {75, 90}, {40, 45}, {5, 30}, {65, 40}};
    int n = p.size();
    auto d = [&](int a, int b) { return std::hypot(p[a].first - p[b].first, p[a].second - p[b].second); };
    std::vector<double> best(n, 1e18);
    std::vector<int> parent(n, -1);
    std::vector<bool> done(n, false);
    std::vector<std::vector<int>> child(n);
    best[0] = 0;
    double mst = 0;
    for (int it = 0; it < n; it++) {
        int u = -1;
        for (int v = 0; v < n; v++) if (!done[v] && (u < 0 || best[v] < best[u])) u = v;
        done[u] = true;
        if (parent[u] >= 0) { child[parent[u]].push_back(u); mst += d(u, parent[u]); }
        for (int v = 0; v < n; v++) if (!done[v] && d(u, v) < best[v]) { best[v] = d(u, v); parent[v] = u; }
    }
    std::vector<int> tour;
    std::function<void(int)> dfs = [&](int u) { tour.push_back(u); for (int v : child[u]) dfs(v); };
    dfs(0);
    double len = 0;
    for (int i = 0; i < n; i++) len += d(tour[i], tour[(i + 1) % n]);
    std::printf("tour:");
    for (int v : tour) std::printf(" %d", v);
    std::printf(" 0\nMST %.1f, tour %.1f, bound 2*MST %.1f\n", mst, len, 2 * mst);
}
tour: 0 5 2 4 7 3 1 6 0
MST 217.8, tour 326.8, bound 2*MST 435.6

An instance where the factor 2 is real

Take a centre cc and kk leaves v0,…,vk−1v_0, \ldots, v_{k-1}. Put c(c,vi)=1c(c, v_i) = 1, give the leaves a cycle of cheap edges of cost 1+δ1 + \delta in the order v0,v2,v4,…,v1,v3,…v_0, v_2, v_4, \ldots, v_1, v_3, \ldots (even indices first, then odd), and let every other leaf pair cost 2, the distance through the centre. The costs are metric. The unique MST is the star, of cost kk. A tour must use k+1k + 1 edges, at most two of them at the centre, so OPT≥2+(k−1)(1+δ)\text{OPT} \ge 2 + (k - 1)(1 + \delta), and going around the cheap cycle attains it. The double-tree algorithm, visiting the leaves in index order, steps from viv_i to vi+1v_{i+1}, which are never consecutive on the cheap cycle, and pays 2 almost every time.

python · try it yourself
def instance(k, delta):
    n = k + 1                                    # vertex 0 is the centre, leaf i is vertex i + 1
    c = [[0.0 if a == b else 2.0 for b in range(n)] for a in range(n)]
    for i in range(1, n):
        c[0][i] = c[i][0] = 1.0
    order = list(range(0, k, 2)) + list(range(1, k, 2))
    for a, b in zip(order, order[1:] + order[:1]):
        c[a + 1][b + 1] = c[b + 1][a + 1] = 1 + delta
    return c

for k in [5, 9, 17, 33, 65]:
    c = instance(k, 0.01)
    tour = list(range(k + 1))                    # preorder of the star: centre, then leaves by index
    alg = sum(c[tour[i]][tour[(i + 1) % (k + 1)]] for i in range(k + 1))
    opt = 2 + (k - 1) * 1.01
    print(f"k = {k:2}: MST {k:2}, double tree {alg:6.2f}, OPT {opt:6.2f}, ratio {alg / opt:.3f}")
k =  5: MST  5, double tree  10.00, OPT   6.04, ratio 1.656
k =  9: MST  9, double tree  18.00, OPT  10.08, ratio 1.786
k = 17: MST 17, double tree  34.00, OPT  18.16, ratio 1.872
k = 33: MST 33, double tree  66.00, OPT  34.32, ratio 1.923
k = 65: MST 65, double tree 130.00, OPT  66.64, ratio 1.951

The ratio approaches 2 as kk grows: the analysis cannot be improved. The waste is in step 2: doubling every tree edge is far more than needed to make the degrees even. Christofides' algorithm fixes exactly that (Christofides' Algorithm).

Other constructive heuristics

  • Nearest addition / nearest insertion (Rosenkrantz, Stearns and Lewis, 1977) grow a tour by repeatedly inserting the vertex closest to it. Both are 2-approximations; the analysis relates the insertion steps to Prim's algorithm.
  • Nearest neighbour (always go to the closest unvisited vertex) is only an O(log⁡n)O(\log n)-approximation, and that is tight up to the constant.
  • 2-opt and Lin-Kernighan local search have no constant worst-case guarantee, but in practice start from such a tour and get within a few percent of optimal.

Test yourself

Why may the double-tree algorithm skip already visited vertices without increasing the cost?

  1. Because the MST has no cycles
  2. Because of the triangle inequality: a direct edge is never longer than the path it replaces
  3. Because Euler circuits never repeat vertices
  4. Because all costs are equal

Why does doubling the MST give a multigraph with an Euler circuit?

  1. Every tree has an Euler circuit
  2. Doubling makes every degree even and the tree is connected
  3. Because the MST is a path
  4. Because the costs are metric

In the star instance, which part of the analysis is loose?

  1. MST≤OPT\text{MST} \le \text{OPT}
  2. Shortcutting saves almost nothing, and the doubled tree costs about twice OPT because OPT is close to the MST cost
  3. The Euler circuit is not unique
  4. The triangle inequality fails