TExcelTAD

Link-Cut Trees

Euler-tour trees maintain a forest under LINK and CUT and answer questions about whole trees. Many algorithms need questions about paths instead: the heaviest edge between uu and vv, the sum of weights from vv to its root, the root itself. Link-cut trees (Sleator and Tarjan, 1983 with biased search trees; 1985 with splay trees, the version here) support

  • LINK(u,v)(u, v), CUT(u,v)(u, v), FIND-ROOT(v)(v), CONNECTED(u,v)(u, v),
  • MAKE-ROOT(v)(v) (re-hang the tree from vv),
  • aggregates over the path from uu to vv (minimum, maximum, sum, with updates to a whole path),

each in O(lg⁡n)O(\lg n) amortized time. They are the engine of fast max-flow algorithms (Dinic's algorithm in O(VElg⁡V)O(V E \lg V)), of dynamic minimum spanning forests and of many network problems.

Preferred paths

Root each tree of the forest (the represented tree). Every node vv has at most one preferred child: the child in whose subtree the most recent ACCESS (defined below) ended, or none if the last access ended at vv itself or nothing below vv has been accessed. Following preferred children from any node gives a preferred path, and the preferred paths partition the nodes.

Each preferred path is stored in an auxiliary tree: a splay tree whose in-order sequence is the path from top to bottom (keyed by depth). The auxiliary tree of a path also keeps a path-parent pointer from its root to the represented-tree parent of the path's top node. In the code, one par array holds both kinds of pointers: a node xx is the root of its auxiliary tree exactly when its par does not list it as a child.

ACCESS: the one real operation

ACCESS(v)(v) makes the path from the root of the represented tree to vv preferred (and vv the bottom of it, with no preferred child), and leaves vv at the root of that path's auxiliary tree.

text
ACCESS(v)
1  last = NIL; y = v
2  while y != NIL
3      SPLAY(y)                       // y becomes the root of its auxiliary tree
4      y.right = last                 // the path below y switches to the one we came from
5      update y's aggregate
6      last = y; y = y.path_parent    // jump to the path above
7  SPLAY(v)

Line 4 is a preferred-child change: the old lower part of yy's path becomes its own path (its root keeps yy as path-parent), and the path containing vv is attached instead. Every other operation is a few ACCESS calls:

  • FIND-ROOT(v)(v): ACCESS(v)(v), then walk to the leftmost node of vv's auxiliary tree (the shallowest node of the path) and splay it.
  • MAKE-ROOT(v)(v): ACCESS(v)(v), then reverse the root-to-vv path, so that vv becomes the top. Reversal is a lazy flag pushed down during splays.
  • LINK(u,v)(u, v): MAKE-ROOT(u)(u), then set uu's path-parent to vv.
  • CUT(u,v)(u, v): MAKE-ROOT(u)(u), ACCESS(v)(v); now the path is exactly u,vu, v, and uu is vv's left child: detach it.
  • PATH-AGGREGATE(u,v)(u, v): MAKE-ROOT(u)(u), ACCESS(v)(v); the auxiliary tree rooted at vv holds exactly the uu-vv path, so its root's aggregate is the answer.

An implementation

The code keeps the nodes in arrays, with ch for splay children, par for parents and path-parents, rev for the lazy reversal, and val/agg for the path maximum. Counters record splay rotations and preferred-child changes.

python · try it yourself
NEG = (float("-inf"), 0)                       # (weight, node id): the path maximum and where it is

class LinkCut:
    """Link-cut tree on nodes 1..n (0 is null). val/agg: path maximum, rev: lazy reversal for make_root."""
    def __init__(self, n, vals=None):
        self.ch = [[0, 0] for _ in range(n + 1)]
        self.par = [0] * (n + 1)
        self.rev = [False] * (n + 1)
        self.val = [NEG] + (vals or [NEG] * n)
        self.agg = self.val[:]
        self.rotations = self.switches = 0
    def _is_root(self, x):                      # root of its auxiliary splay tree
        p = self.par[x]
        return p == 0 or (self.ch[p][0] != x and self.ch[p][1] != x)
    def _push(self, x):
        if self.rev[x]:
            l, r = self.ch[x]
            self.ch[x] = [r, l]
            for c in (l, r):
                if c: self.rev[c] = not self.rev[c]
            self.rev[x] = False
    def _pull(self, x):
        l, r = self.ch[x]
        self.agg[x] = max(self.val[x], self.agg[l] if l else NEG, self.agg[r] if r else NEG)
    def _rotate(self, x):
        self.rotations += 1
        p, g = self.par[x], self.par[self.par[x]]
        d = 1 if self.ch[p][1] == x else 0
        b = self.ch[x][1 - d]
        if not self._is_root(p):                # p's place under g goes to x
            self.ch[g][1 if self.ch[g][1] == p else 0] = x
        self.par[x] = g                          # (if p was an aux root, x inherits its path-parent)
        self.ch[p][d] = b
        if b: self.par[b] = p
        self.ch[x][1 - d] = p
        self.par[p] = x
        self._pull(p); self._pull(x)
    def _splay(self, x):
        path, y = [x], x
        while not self._is_root(y):
            y = self.par[y]; path.append(y)
        for y in reversed(path): self._push(y)
        while not self._is_root(x):
            p = self.par[x]
            if not self._is_root(p):
                g = self.par[p]
                zigzig = (self.ch[g][0] == p) == (self.ch[p][0] == x)
                self._rotate(p if zigzig else x)
            self._rotate(x)
    def access(self, x):                        # make the root-to-x path preferred; x ends at the aux root
        last, y = 0, x
        while y:
            self._splay(y)
            if self.ch[y][1] != last: self.switches += 1
            self.ch[y][1] = last
            self._pull(y)
            last, y = y, self.par[y]
        self._splay(x)
    def make_root(self, x):
        self.access(x)
        self.rev[x] = not self.rev[x]
    def find_root(self, x):
        self.access(x)
        while True:
            self._push(x)
            if not self.ch[x][0]: break
            x = self.ch[x][0]
        self._splay(x)
        return x
    def connected(self, u, v):
        return u == v or self.find_root(u) == self.find_root(v)
    def link(self, u, v):                       # u, v in different trees
        self.make_root(u)
        self.par[u] = v
    def cut(self, u, v):                        # (u, v) is a tree edge
        self.make_root(u)
        self.access(v)
        self.ch[v][0] = 0
        self.par[u] = 0
        self._pull(v)
    def path_max(self, u, v):                   # (max, node) on the u-v path
        self.make_root(u)
        self.access(v)
        return self.agg[v]

import random

rng = random.Random(1983)
n, m = 60, 400
edges = []
for i in range(m):
    u, v = rng.sample(range(1, n + 1), 2)
    edges.append((u, v, rng.randrange(1, 1000)))

# Vertices are nodes 1..n (no weight); edge i is node n + 1 + i, carrying (weight, its node id).
vals = [NEG] * n + [(w, n + 1 + i) for i, (_, _, w) in enumerate(edges)]
lc = LinkCut(n + m, vals)
ends, total, changes = {}, 0, 0
for i, (u, v, w) in enumerate(edges):
    e = n + 1 + i
    if not lc.connected(u, v):
        lc.link(u, e); lc.link(e, v); ends[e] = (u, v); total += w
    else:
        (mw, me) = lc.path_max(u, v)             # heaviest edge on the cycle the new edge would close
        if mw > w:
            a, b = ends.pop(me)
            lc.cut(a, me); lc.cut(me, b); total -= mw
            lc.link(u, e); lc.link(e, v); ends[e] = (u, v); total += w
            changes += 1

parent = list(range(n + 1))                      # Kruskal with union-find, for comparison
def find(x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]; x = parent[x]
    return x
kruskal = 0
for u, v, w in sorted(edges, key=lambda e: e[2]):
    if find(u) != find(v):
        parent[find(u)] = find(v); kruskal += w
print(f"{m} edges inserted one by one into a forest on {n} vertices")
print(f"tree edges replaced along the way: {changes}; final forest weight {total}; Kruskal: {kruskal}")
print(f"splay rotations per edge insertion: {lc.rotations / m:.1f}")
400 edges inserted one by one into a forest on 60 vertices
tree edges replaced along the way: 106; final forest weight 4686; Kruskal: 4686
splay rotations per edge insertion: 20.3

The application is the dynamic minimum spanning forest under edge insertions: when a new edge closes a cycle, the heaviest edge on that cycle is the heaviest edge on the tree path between its endpoints. If it is heavier than the new edge, swap them (the cycle property of MSTs). Each edge is a node of its own, so that edge weights become node values. The result matches Kruskal's algorithm run on all edges at once.

In C++

The same structure and the same incremental MST, with random edges drawn from std::mt19937, again checked against Kruskal.

cpp · try it yourself
#include <algorithm>
#include <array>
#include <cstdio>
#include <numeric>
#include <random>
#include <utility>
#include <vector>

// Link-cut tree with path maximum: agg[x] = (largest weight, node holding it) in x's splay subtree.
class LinkCut {
    using Val = std::pair<int, int>;
    std::vector<std::array<int, 2>> ch;
    std::vector<int> par;
    std::vector<char> rev;
    std::vector<Val> val, agg;
    bool is_root(int x) const { int p = par[x]; return p == 0 || (ch[p][0] != x && ch[p][1] != x); }
    void push(int x) {
        if (!rev[x]) return;
        std::swap(ch[x][0], ch[x][1]);
        for (int c : ch[x]) if (c) rev[c] ^= 1;
        rev[x] = 0;
    }
    void pull(int x) {
        agg[x] = val[x];
        for (int c : ch[x]) if (c) agg[x] = std::max(agg[x], agg[c]);
    }
    void rotate(int x) {
        int p = par[x], g = par[p], d = ch[p][1] == x, b = ch[x][!d];
        if (!is_root(p)) ch[g][ch[g][1] == p] = x;
        par[x] = g;
        ch[p][d] = b; if (b) par[b] = p;
        ch[x][!d] = p; par[p] = x;
        pull(p); pull(x);
    }
    void splay(int x) {
        std::vector<int> path{x};
        for (int y = x; !is_root(y); y = par[y]) path.push_back(par[y]);
        for (auto it = path.rbegin(); it != path.rend(); ++it) push(*it);
        while (!is_root(x)) {
            int p = par[x];
            if (!is_root(p)) rotate((ch[par[p]][0] == p) == (ch[p][0] == x) ? p : x);
            rotate(x);
        }
    }
    void access(int x) {
        for (int last = 0, y = x; y; last = y, y = par[y]) { splay(y); ch[y][1] = last; pull(y); }
        splay(x);
    }
    void make_root(int x) { access(x); rev[x] ^= 1; }
    int find_root(int x) {
        access(x);
        for (push(x); ch[x][0]; push(x)) x = ch[x][0];
        splay(x);
        return x;
    }
public:
    explicit LinkCut(const std::vector<Val>& vals)            // vals[0] is the null node
        : ch(vals.size(), {0, 0}), par(vals.size(), 0), rev(vals.size(), 0), val(vals), agg(vals) {}
    bool connected(int u, int v) { return find_root(u) == find_root(v); }
    void link(int u, int v) { make_root(u); par[u] = v; }
    void cut(int u, int v) { make_root(u); access(v); ch[v][0] = 0; par[u] = 0; pull(v); }
    Val path_max(int u, int v) { make_root(u); access(v); return agg[v]; }
};

int main() {
    const int n = 60, m = 400;
    std::mt19937 rng(1983);
    struct Edge { int u, v, w; };
    std::vector<Edge> edges;
    while (static_cast<int>(edges.size()) < m) {
        int u = 1 + static_cast<int>(rng() % n);
        int v = 1 + static_cast<int>(rng() % n);
        int w = 1 + static_cast<int>(rng() % 999);
        if (u != v) edges.push_back({u, v, w});
    }
    std::vector<std::pair<int, int>> vals(n + m + 1, {-1, 0});  // vertices: weight -1, below every edge
    for (int i = 0; i < m; ++i) vals[n + 1 + i] = {edges[i].w, n + 1 + i};
    LinkCut lc(vals);
    std::vector<std::pair<int, int>> ends(n + m + 1);
    long total = 0;
    int replaced = 0;
    for (int i = 0; i < m; ++i) {
        auto [u, v, w] = edges[i];
        int e = n + 1 + i;
        if (lc.connected(u, v)) {
            auto [mw, me] = lc.path_max(u, v);
            if (mw <= w) continue;
            lc.cut(ends[me].first, me); lc.cut(me, ends[me].second);
            total -= mw; ++replaced;
        }
        lc.link(u, e); lc.link(e, v); ends[e] = {u, v}; total += w;
    }
    std::vector<int> parent(n + 1);                          // Kruskal for comparison
    std::iota(parent.begin(), parent.end(), 0);
    auto find = [&](int x) { while (parent[x] != x) x = parent[x] = parent[parent[x]]; return x; };
    std::sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) { return a.w < b.w; });
    long kruskal = 0;
    for (auto [u, v, w] : edges) if (find(u) != find(v)) { parent[find(u)] = find(v); kruskal += w; }
    std::printf("replaced %d tree edges; link-cut forest weight %ld, Kruskal %ld\n", replaced, total, kruskal);
}
replaced 109 tree edges; link-cut forest weight 4799, Kruskal 4799

Why ACCESS is O(lg⁡n)O(\lg n) amortized

The proof has two parts. Both are amortized; a single ACCESS can take Θ(n)\Theta(n) time (for instance the first access to the bottom of a long path).

1. Preferred-child changes: O(lg⁡n)O(\lg n) amortized per ACCESS. Call a tree edge from vv to its child cc heavy if cc's subtree has more than half of vv's descendants, and light otherwise. Any root-to-node path has at most lg⁡n\lg n light edges, since each one at least halves the subtree size. A change on line 4 makes some edge preferred. If it is light, charge it to the at most lg⁡n\lg n light edges on the accessed path. If it is heavy, the heavy edge that becomes preferred was non-preferred; a heavy edge becomes non-preferred only when a light sibling edge becomes preferred (already charged), or when an access ends at its upper node (once per access); otherwise it was non-preferred from the start (n−1n - 1 edges). Each time a heavy edge becomes preferred it must have become non-preferred before, so heavy changes are bounded by light changes plus mm plus n−1n - 1. So mm accesses make O(mlg⁡n+n)O(m \lg n + n) changes. (LINK and CUT change subtree sizes, but only along one path, which adds O(lg⁡n)O(\lg n) light edges per operation.)

2. The splays: O(lg⁡n)O(\lg n) amortized per ACCESS in total. Give each node a weight equal to the number of nodes in its auxiliary subtree including the auxiliary trees hanging below it by path-parent pointers (its subtree in the "tree of auxiliary trees"). With the potential Φ=∑xlg⁡(weight(x))\Phi = \sum_x \lg(\text{weight}(x)), the access lemma of splay trees says that splaying yy to the root of its auxiliary tree costs 3(lg⁡W−lg⁡w(y))+13(\lg W - \lg w(y)) + 1 amortized, where WW is the weight of the auxiliary tree's root. Along one ACCESS these terms telescope: the root of one auxiliary tree is a descendant of the next node splayed, so the sum is 3lg⁡n+O(number of preferred-child changes)3 \lg n + O(\text{number of preferred-child changes}), which is O(lg⁡n)O(\lg n) amortized by part 1.

The next program measures both quantities on a random tree and on a path of nn nodes over 3000 random accesses.

python · try it yourself
NEG = (float("-inf"), 0)                       # (weight, node id): the path maximum and where it is

class LinkCut:
    """Link-cut tree on nodes 1..n (0 is null). val/agg: path maximum, rev: lazy reversal for make_root."""
    def __init__(self, n, vals=None):
        self.ch = [[0, 0] for _ in range(n + 1)]
        self.par = [0] * (n + 1)
        self.rev = [False] * (n + 1)
        self.val = [NEG] + (vals or [NEG] * n)
        self.agg = self.val[:]
        self.rotations = self.switches = 0
    def _is_root(self, x):                      # root of its auxiliary splay tree
        p = self.par[x]
        return p == 0 or (self.ch[p][0] != x and self.ch[p][1] != x)
    def _push(self, x):
        if self.rev[x]:
            l, r = self.ch[x]
            self.ch[x] = [r, l]
            for c in (l, r):
                if c: self.rev[c] = not self.rev[c]
            self.rev[x] = False
    def _pull(self, x):
        l, r = self.ch[x]
        self.agg[x] = max(self.val[x], self.agg[l] if l else NEG, self.agg[r] if r else NEG)
    def _rotate(self, x):
        self.rotations += 1
        p, g = self.par[x], self.par[self.par[x]]
        d = 1 if self.ch[p][1] == x else 0
        b = self.ch[x][1 - d]
        if not self._is_root(p):                # p's place under g goes to x
            self.ch[g][1 if self.ch[g][1] == p else 0] = x
        self.par[x] = g                          # (if p was an aux root, x inherits its path-parent)
        self.ch[p][d] = b
        if b: self.par[b] = p
        self.ch[x][1 - d] = p
        self.par[p] = x
        self._pull(p); self._pull(x)
    def _splay(self, x):
        path, y = [x], x
        while not self._is_root(y):
            y = self.par[y]; path.append(y)
        for y in reversed(path): self._push(y)
        while not self._is_root(x):
            p = self.par[x]
            if not self._is_root(p):
                g = self.par[p]
                zigzig = (self.ch[g][0] == p) == (self.ch[p][0] == x)
                self._rotate(p if zigzig else x)
            self._rotate(x)
    def access(self, x):                        # make the root-to-x path preferred; x ends at the aux root
        last, y = 0, x
        while y:
            self._splay(y)
            if self.ch[y][1] != last: self.switches += 1
            self.ch[y][1] = last
            self._pull(y)
            last, y = y, self.par[y]
        self._splay(x)
    def make_root(self, x):
        self.access(x)
        self.rev[x] = not self.rev[x]
    def find_root(self, x):
        self.access(x)
        while True:
            self._push(x)
            if not self.ch[x][0]: break
            x = self.ch[x][0]
        self._splay(x)
        return x
    def connected(self, u, v):
        return u == v or self.find_root(u) == self.find_root(v)
    def link(self, u, v):                       # u, v in different trees
        self.make_root(u)
        self.par[u] = v
    def cut(self, u, v):                        # (u, v) is a tree edge
        self.make_root(u)
        self.access(v)
        self.ch[v][0] = 0
        self.par[u] = 0
        self._pull(v)
    def path_max(self, u, v):                   # (max, node) on the u-v path
        self.make_root(u)
        self.access(v)
        return self.agg[v]

import random, math

rng = random.Random(85)
for shape in ["random tree", "path"]:
    for n in [256, 4096]:
        lc = LinkCut(n)
        for v in range(2, n + 1):               # a fresh forest is just path-parent pointers
            lc.par[v] = rng.randrange(1, v) if shape == "random tree" else v - 1
        lc.rotations = lc.switches = 0
        q = 3000
        for _ in range(q):
            lc.access(rng.randrange(1, n + 1))
        print(f"{shape:11}, n = {n:4}: per access {lc.switches / q:5.2f} preferred-child changes, "
              f"{lc.rotations / q:5.2f} rotations; lg n = {math.log2(n):.0f}")
random tree, n =  256: per access  3.03 preferred-child changes,  7.34 rotations; lg n = 8
random tree, n = 4096: per access  4.49 preferred-child changes, 10.98 rotations; lg n = 12
path       , n =  256: per access  2.04 preferred-child changes,  8.75 rotations; lg n = 8
path       , n = 4096: per access  3.35 preferred-child changes, 16.37 rotations; lg n = 12

From n=256n = 256 to n=4096n = 4096, four doublings, the averages grow by about 1.4 preferred-child changes and 4 to 8 rotations: logarithmic growth, with the preferred-child changes well below lg⁡n\lg n. A path, the shape where a naive "walk up" structure would cost Θ(n)\Theta(n), costs a few more rotations but nothing like nn.

Note: Sleator and Tarjan's original version with biased search trees achieves O(lg⁡n)O(\lg n) worst case per operation, at the cost of a far more complicated structure. The splay version is the one used in practice. Top trees (Alstrup, Holm, de Lichtenberg and Thorup, 2005) generalize both Euler-tour and link-cut trees and support path and subtree aggregates together, also in O(lg⁡n)O(\lg n).

Test yourself

What does ACCESS(v)(v) guarantee when it returns?

  1. vv is the root of the represented tree
  2. The path from the root of the represented tree to vv is one preferred path, vv has no preferred child, and vv is the root of that path's auxiliary tree
  3. Every node on vv's path has been splayed to the global root
  4. vv's subtree is stored in one splay tree

Why are there at most lg⁡n\lg n light edges on any root-to-node path?

  1. Because light edges are never preferred
  2. Because crossing a light edge downward at least halves the subtree size
  3. Because the tree is balanced
  4. Because splaying removes them

Which bound do splay-based link-cut trees give for LINK, CUT and path queries?

  1. O(lg⁡n)O(\lg n) worst case
  2. O(lg⁡n)O(\lg n) amortized
  3. O(lg⁡2n)O(\lg^2 n) amortized
  4. O(1)O(1) expected