TExcelTAD
Home › Graph Algorithms › Uniqueness and the Cycle Property

Uniqueness and the Cycle Property

Kruskal and Prim found the same tree on the graph of the previous lessons. Was that luck? This lesson answers when the minimum spanning tree is unique, proves the mirror image of the cut property, the cycle property, and turns it into two more tools: an algorithm that deletes edges instead of adding them, and a test that checks whether a given spanning tree is minimum.

Ties make several MSTs

If several edges have the same weight, different tie-breaking rules can produce different trees of the same minimum weight. A square with four edges of weight 1 and a diagonal of weight 2 has four minimum spanning trees, one for each side left out. Kruskal (ties broken by name in the animation) picks one of them.

python · try it yourself
from itertools import combinations

def spanning_trees(V, edges):
    for subset in combinations(edges, len(V) - 1):
        parent = {v: v for v in V}
        def find(x):
            while parent[x] != x:
                x = parent[x]
            return x
        ok = True
        for u, v, _ in subset:
            a, b = find(u), find(v)
            if a == b:
                ok = False
                break
            parent[a] = b
        if ok:
            yield subset

def msts(V, edges):
    trees = list(spanning_trees(V, edges))
    best = min(sum(w for *_, w in t) for t in trees)
    return best, [t for t in trees if sum(w for *_, w in t) == best]

square = [("A", "B", 1), ("B", "C", 1), ("C", "D", 1), ("A", "D", 1), ("A", "C", 2)]
best, trees = msts("ABCD", square)
print(f"square: MST weight {best}, {len(trees)} minimum spanning trees")
for t in trees:
    print("  ", " ".join(f"{u}{v}" for u, v, _ in t))

tied = [("A", "B", 1), ("B", "C", 2), ("C", "D", 2), ("A", "C", 3)]
best, trees = msts("ABCD", tied)
print(f"two edges of weight 2: MST weight {best}, {len(trees)} tree(s)")
square: MST weight 3, 4 minimum spanning trees
   AB BC CD
   AB BC AD
   AB CD AD
   BC CD AD
two edges of weight 2: MST weight 5, 1 tree(s)

The second graph shows that ties do not force several MSTs: its two edges of weight 2 are not competing for the same place (they lie on no common cycle), so both are in the tree, and the MST is unique. What uniqueness needs is that no two equal edges can be exchanged for each other. Distinct weights rule that out completely, as the theorem below proves.

Theorem. If all edge weights of a connected graph are distinct, the graph has exactly one minimum spanning tree.

Proof

Suppose T1≠T2T_1 \ne T_2 are both MSTs, and let ee be the lightest edge that is in exactly one of them, say e∈T1∖T2e \in T_1 \setminus T_2. Adding ee to T2T_2 creates a cycle, and that cycle contains an edge f∉T1f \notin T_1 (otherwise the cycle would lie entirely in T1T_1). So ff is in exactly one of the trees, and by the choice of ee and distinct weights, w(f)>w(e)w(f) > w(e). Then T2∖{f}∪{e}T_2 \setminus \{f\} \cup \{e\} is a spanning tree lighter than T2T_2, a contradiction.

The converse is false: a tree that is the whole graph has a unique MST whatever its weights.

The cycle property

Theorem (cycle property). Let CC be any cycle of GG and let ee be an edge of CC that is strictly heavier than every other edge of CC. Then ee belongs to no minimum spanning tree.

Proof

Suppose an MST TT contains e=(u,v)e = (u, v). Removing ee splits TT into two pieces, one containing uu and one containing vv, which defines a cut. The rest of the cycle CC is a path from uu to vv, so it crosses that cut at some edge f≠ef \ne e. Then T∖{e}∪{f}T \setminus \{e\} \cup \{f\} is a spanning tree, and since w(f)<w(e)w(f) < w(e) it is lighter than TT, a contradiction.

The cut property says which edges are safe to take; the cycle property says which are safe to discard. It gives a third MST algorithm, reverse-delete: go through the edges from heaviest to lightest, and delete each one whose removal leaves the graph connected. A deleted edge is the heaviest on some cycle that still exists (the cycle through the path that keeps the graph connected), so with distinct weights it is in no MST.

python · try it yourself
def connected(V, edges):
    adj = {v: [] for v in V}
    for u, v, _ in edges:
        adj[u].append(v); adj[v].append(u)
    seen, stack = {V[0]}, [V[0]]
    while stack:
        for y in adj[stack.pop()]:
            if y not in seen:
                seen.add(y); stack.append(y)
    return len(seen) == len(V)

def reverse_delete(V, edges):
    kept = sorted(edges, key=lambda e: -e[2])
    for e in sorted(edges, key=lambda e: -e[2]):
        rest = [f for f in kept if f != e]
        if connected(V, rest):
            kept = rest
            print(f"delete {e[0]}-{e[1]} ({e[2]:2}): still connected")
        else:
            print(f"keep   {e[0]}-{e[1]} ({e[2]:2}): it is a bridge now")
    return kept

edges = [("A", "B", 4), ("A", "C", 3), ("B", "C", 2), ("B", "D", 5), ("C", "E", 7), ("D", "E", 6),
         ("D", "F", 9), ("E", "G", 8), ("F", "G", 10), ("F", "H", 1), ("G", "H", 11), ("E", "F", 12)]
tree = reverse_delete("ABCDEFGH", edges)
print("weight", sum(w for *_, w in tree), "tree:", " ".join(sorted(f"{u}{v}" for u, v, _ in tree)))
delete E-F (12): still connected
delete G-H (11): still connected
delete F-G (10): still connected
keep   D-F ( 9): it is a bridge now
keep   E-G ( 8): it is a bridge now
delete C-E ( 7): still connected
keep   D-E ( 6): it is a bridge now
keep   B-D ( 5): it is a bridge now
delete A-B ( 4): still connected
keep   A-C ( 3): it is a bridge now
keep   B-C ( 2): it is a bridge now
keep   F-H ( 1): it is a bridge now
weight 34 tree: AC BC BD DE DF EG FH

It ends with the same tree of weight 34 that Kruskal and Prim built on this graph, as it must: the weights are distinct, so there is only one. Each connectivity test costs O(V+E)O(V + E), so this simple version takes O(E(V+E))O(E(V + E)); it is a proof device more than a practical algorithm.

In C++

The C++ version of reverse-delete uses an iterative DFS for each connectivity test.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <vector>

struct Edge { int w; char u, v; bool alive; };

bool connected(int n, const std::vector<Edge>& edges) {
    std::vector<std::vector<int>> adj(n);
    for (const auto& e : edges)
        if (e.alive) { adj[e.u - 'A'].push_back(e.v - 'A'); adj[e.v - 'A'].push_back(e.u - 'A'); }
    std::vector<bool> seen(n, false);
    std::vector<int> stack = {0};
    seen[0] = true;
    int count = 1;
    while (!stack.empty()) {
        int x = stack.back(); stack.pop_back();
        for (int y : adj[x]) if (!seen[y]) { seen[y] = true; ++count; stack.push_back(y); }
    }
    return count == n;
}

int main() {
    std::vector<Edge> edges = {{4,'A','B',true}, {3,'A','C',true}, {2,'B','C',true}, {5,'B','D',true},
                               {7,'C','E',true}, {6,'D','E',true}, {9,'D','F',true}, {8,'E','G',true},
                               {10,'F','G',true}, {1,'F','H',true}, {11,'G','H',true}, {12,'E','F',true}};
    std::sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) { return a.w > b.w; });
    for (auto& e : edges) {
        e.alive = false;
        if (!connected(8, edges)) e.alive = true;            // a bridge: put it back
    }
    int total = 0;
    std::printf("kept:");
    for (const auto& e : edges)
        if (e.alive) { std::printf(" %c%c", e.u, e.v); total += e.w; }
    std::printf("\nweight %d\n", total);
}
kept: DF EG DE BD AC BC FH
weight 34

Verifying a spanning tree

The cycle property also gives a certificate of optimality. Every non-tree edge (u,v)(u, v) closes a cycle with the tree path from uu to vv.

Theorem. A spanning tree TT is an MST if and only if every non-tree edge (u,v)(u, v) is at least as heavy as every edge on the tree path between uu and vv.

If some non-tree edge were lighter than an edge on its tree path, swapping them would give a lighter tree, so the condition is necessary. Conversely, if it holds, run Kruskal with ties broken in favour of tree edges: by the time a non-tree edge is examined, every edge of its tree path has been examined and accepted, so the non-tree edge is rejected, and Kruskal returns exactly TT. The program checks two candidate trees.

python · try it yourself
def path_max(tree, u, v):
    adj = {}
    for a, b, w in tree:
        adj.setdefault(a, []).append((b, w)); adj.setdefault(b, []).append((a, w))
    best = {u: (0, None)}                   # vertex -> (heaviest edge weight on path from u, that edge)
    stack = [u]
    while stack:
        x = stack.pop()
        for y, w in adj[x]:
            if y not in best:
                best[y] = max(best[x], (w, f"{x}{y}"))
                stack.append(y)
    return best[v]

def verify(edges, tree):
    in_tree = {(u, v) for u, v, _ in tree}
    for u, v, w in edges:
        if (u, v) not in in_tree:
            heaviest, which = path_max(tree, u, v)
            if w < heaviest:
                return f"not minimum: non-tree edge {u}{v} ({w}) is lighter than tree edge {which} ({heaviest})"
    return "minimum: every non-tree edge is a heaviest edge on its cycle"

edges = [("A", "B", 4), ("A", "C", 3), ("B", "C", 2), ("B", "D", 5), ("C", "E", 7), ("D", "E", 6),
         ("D", "F", 9), ("E", "G", 8), ("F", "G", 10), ("F", "H", 1), ("G", "H", 11), ("E", "F", 12)]
mst = [e for e in edges if e[:2] in {("A", "C"), ("B", "C"), ("B", "D"), ("D", "E"), ("D", "F"), ("E", "G"), ("F", "H")}]
other = [e for e in edges if e[:2] in {("A", "B"), ("B", "C"), ("B", "D"), ("D", "E"), ("D", "F"), ("E", "G"), ("F", "H")}]
print("tree 1:", verify(edges, mst))
print("tree 2:", verify(edges, other))
tree 1: minimum: every non-tree edge is a heaviest edge on its cycle
tree 2: not minimum: non-tree edge AC (3) is lighter than tree edge AB (4)

With a cleverer path-maximum structure the check runs in linear time, which is one ingredient of the randomized linear-time MST algorithm of Karger, Klein and Tarjan.

Test yourself

All edge weights of a connected graph are distinct. How many minimum spanning trees does it have?

  1. Exactly one
  2. At least two
  3. It depends on the number of cycles
  4. V−1V - 1

Edge ee is strictly the heaviest edge on some cycle. What does the cycle property say?

  1. ee is in every MST
  2. ee is in no MST
  3. ee is in some MST
  4. Nothing unless weights are distinct

A spanning tree TT has a non-tree edge (u,v)(u, v) of weight 5, and the tree path from uu to vv contains an edge of weight 8. What can you conclude?

  1. TT is an MST
  2. TT is not an MST: swapping the two edges saves 3
  3. The graph has a negative cycle
  4. Nothing