Mini Project: A Minimum-Cut Finder with Measured Success Rates
The lessons on Karger's contraction algorithm and Karger-Stein proved lower bounds on success probabilities. In this project you build a small minimum-cut tool around both algorithms and measure what the bounds promise: the success rate of a single run, how many runs a target confidence needs, and what each algorithm spends. A deterministic algorithm (Stoer-Wagner) provides the ground truth, so every measured success is checked against the true minimum.
Each step is a complete program; later steps repeat the pieces they need, so you can run any of them on its own. Every random choice comes from a seeded generator, so the numbers below are exactly what you will see.
Step 1: Test graphs and a deterministic baseline
Four families of multigraphs, each with a known structure:
- two cliques: two joined by 2 edges (the bridges are the unique minimum cut);
- doubled cycle: a 20-cycle with every edge doubled except two opposite ones (minimum cut 2, many cuts of size 3 and 4);
- heavy cycle: a 20-cycle with every edge of multiplicity 4 except two opposite edges of multiplicity 3 (minimum cut 6, unique);
- planted: two random halves of 10 vertices with edge probability inside, joined by 3 random edges.
The baseline is the Stoer-Wagner algorithm (1997), which finds a minimum cut deterministically in time with simple arrays: in each phase it adds vertices in order of their connection to the growing set, the last two added vertices give a "cut of the phase", and then they are merged.
import random
def stoer_wagner(n, edges):
w = [[0] * n for _ in range(n)]
for u, v in edges:
w[u][v] += 1
w[v][u] += 1
groups = [[v] for v in range(n)]
alive = list(range(n))
best, best_side = None, None
while len(alive) > 1:
added = [alive[0]]
conn = {v: w[alive[0]][v] for v in alive[1:]}
while conn:
nxt = max(conn, key=lambda v: (conn[v], -v))
last = conn.pop(nxt)
added.append(nxt)
for v in conn:
conn[v] += w[nxt][v]
s, t = added[-2], added[-1]
if best is None or last < best: # the cut of the phase separates t's group
best, best_side = last, sorted(groups[t])
for v in alive:
w[s][v] += w[t][v]
w[v][s] = w[s][v]
w[s][s] = 0
groups[s] += groups[t]
alive.remove(t)
return best, best_side
def test_graphs(rng):
g = {}
e = [(u + s, v + s) for s in (0, 8) for u in range(8) for v in range(u + 1, 8)]
g["two cliques"] = (16, e + [(0, 8), (1, 9)])
g["doubled cycle"] = (20, [(i, (i + 1) % 20) for i in range(20) for _ in range(1 if i in (0, 10) else 2)])
g["heavy cycle"] = (20, [(i, (i + 1) % 20) for i in range(20) for _ in range(3 if i in (0, 10) else 4)])
e = [(u, v) for u in range(20) for v in range(u + 1, 20) if (u < 10) == (v < 10) and rng.random() < 0.6]
g["planted"] = (20, e + [(rng.randrange(10), rng.randrange(10, 20)) for _ in range(3)])
return g
graphs = test_graphs(random.Random(200))
for name, (n, edges) in graphs.items():
k, side = stoer_wagner(n, edges)
print(f"{name:14} n = {n}, m = {len(edges):3}: minimum cut {k}, one side {side}")two cliques n = 16, m = 58: minimum cut 2, one side [8, 9, 10, 11, 12, 13, 14, 15]
doubled cycle n = 20, m = 38: minimum cut 2, one side [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
heavy cycle n = 20, m = 78: minimum cut 6, one side [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
planted n = 20, m = 60: minimum cut 3, one side [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Step 2: Karger's contraction, measured
One contraction run shuffles the edges and merges with union-find until two groups remain. The program runs it 1000 times on each graph and reports the success rate (a run succeeds if its cut has the minimum size), an approximate 95% interval , and the guaranteed bound .
import random
from math import sqrt
def find(p, x):
while p[x] != x:
p[x] = p[p[x]]
x = p[x]
return x
def karger_run(n, edges, rng):
order = edges[:]
rng.shuffle(order)
p, groups = list(range(n)), n
for u, v in order:
if groups == 2:
break
a, b = find(p, u), find(p, v)
if a != b:
p[a] = b
groups -= 1
return sum(find(p, u) != find(p, v) for u, v in edges)
def test_graphs(rng):
g = {}
e = [(u + s, v + s) for s in (0, 8) for u in range(8) for v in range(u + 1, 8)]
g["two cliques"] = (16, e + [(0, 8), (1, 9)])
g["doubled cycle"] = (20, [(i, (i + 1) % 20) for i in range(20) for _ in range(1 if i in (0, 10) else 2)])
g["heavy cycle"] = (20, [(i, (i + 1) % 20) for i in range(20) for _ in range(3 if i in (0, 10) else 4)])
e = [(u, v) for u in range(20) for v in range(u + 1, 20) if (u < 10) == (v < 10) and rng.random() < 0.6]
g["planted"] = (20, e + [(rng.randrange(10), rng.randrange(10, 20)) for _ in range(3)])
return g
minimum = {"two cliques": 2, "doubled cycle": 2, "heavy cycle": 6, "planted": 3} # from Step 1
graphs = test_graphs(random.Random(200))
rng = random.Random(201)
T = 1000
print("graph success rate 95% interval bound 2/(n(n-1))")
for name, (n, edges) in graphs.items():
results = [karger_run(n, edges, rng) for _ in range(T)]
p = results.count(minimum[name]) / T
half = 2 * sqrt(p * (1 - p) / T)
print(f"{name:14} {p:12.4f} [{max(0, p - half):.4f}, {p + half:.4f}] {2 / (n * (n - 1)):.4f}")graph success rate 95% interval bound 2/(n(n-1))
two cliques 0.3950 [0.3641, 0.4259] 0.0083
doubled cycle 0.0490 [0.0353, 0.0627] 0.0053
heavy cycle 0.0140 [0.0066, 0.0214] 0.0053
planted 0.2670 [0.2390, 0.2950] 0.0053
Every measured rate is above the worst-case bound, by a factor of more than 2 on the heavy cycle and of about 50 on the planted graph: the bound is tight only for graphs like the plain cycle, where every pair of edges is a minimum cut.
Step 3: Karger-Stein, measured
Karger-Stein contracts to vertices twice independently, recurses on both, and brute-forces graphs with at most 6 vertices. The program counts work as edges processed (shuffling, merging, relabelling, and one unit per vertex pair per cut tried at the leaves), measures 3 trials per graph, and does the same accounting for single contraction runs.
import random
from math import ceil, sqrt
def find(p, x):
while p[x] != x:
p[x] = p[p[x]]
x = p[x]
return x
def contract_to(n, edges, t, rng, work):
order = edges[:]
rng.shuffle(order)
p, groups = list(range(n)), n
for u, v in order:
if groups == t:
break
work[0] += 1
a, b = find(p, u), find(p, v)
if a != b:
p[a] = b
groups -= 1
label = {}
for x in range(n):
label.setdefault(find(p, x), len(label))
work[0] += len(edges)
new = [(label[find(p, u)], label[find(p, v)]) for u, v in edges]
return t, [(a, b) for a, b in new if a != b]
def brute(n, edges, work):
w = {}
for u, v in edges:
w[(u, v)] = w.get((u, v), 0) + 1 # merge parallel edges into weights
best = None
for mask in range(1, 2 ** (n - 1)):
c = sum(c for (u, v), c in w.items() if (mask >> u & 1) != (mask >> v & 1))
work[0] += len(w)
best = c if best is None else min(best, c)
return best
def karger_stein(n, edges, rng, work):
if n <= 6:
return brute(n, edges, work)
t = ceil(1 + n / sqrt(2))
return min(karger_stein(*contract_to(n, edges, t, rng, work), rng, work) for _ in range(2))
def test_graphs(rng):
g = {}
e = [(u + s, v + s) for s in (0, 8) for u in range(8) for v in range(u + 1, 8)]
g["two cliques"] = (16, e + [(0, 8), (1, 9)])
g["doubled cycle"] = (20, [(i, (i + 1) % 20) for i in range(20) for _ in range(1 if i in (0, 10) else 2)])
g["heavy cycle"] = (20, [(i, (i + 1) % 20) for i in range(20) for _ in range(3 if i in (0, 10) else 4)])
e = [(u, v) for u in range(20) for v in range(u + 1, 20) if (u < 10) == (v < 10) and rng.random() < 0.6]
g["planted"] = (20, e + [(rng.randrange(10), rng.randrange(10, 20)) for _ in range(3)])
return g
minimum = {"two cliques": 2, "doubled cycle": 2, "heavy cycle": 6, "planted": 3}
graphs = test_graphs(random.Random(200))
rng = random.Random(202)
print("graph KS successes work per KS trial work per Karger run")
for name, (n, edges) in graphs.items():
w = [0]
ok = sum(karger_stein(n, edges, rng, w) == minimum[name] for _ in range(3))
w1 = [0]
for _ in range(100):
contract_to(n, edges, 2, rng, w1)
print(f"{name:14} {ok:8} of 3 {w[0] / 3:17.0f} {w1[0] / 100:19.0f}")graph KS successes work per KS trial work per Karger run
two cliques 3 of 3 30724 77
doubled cycle 3 of 3 27909 64
heavy cycle 2 of 3 32172 111
planted 3 of 3 57125 86
Karger-Stein succeeds in almost every trial, as its bound suggests, but one trial costs as much as hundreds of contraction runs.
Step 4: A finder with a confidence target
A tool should not rely on measured rates of the very graph it is solving. It should take a failure target and run as many trials as the proved bounds require: for Karger, runs; for Karger-Stein, trials, where is the success bound after levels of the recursion, computed from with . Both versions return the best cut found together with one side of it, and the program checks the answer against Stoer-Wagner on a 14-vertex heavy cycle.
import random
from math import ceil, comb, log, sqrt
def find(p, x):
while p[x] != x:
p[x] = p[p[x]]
x = p[x]
return x
def contract_to(n, edges, t, rng, work):
"""Returns the contracted graph and, for every original vertex, its group label."""
order = edges[:]
rng.shuffle(order)
p, groups = list(range(n)), n
for u, v in order:
if groups == t:
break
work[0] += 1
a, b = find(p, u), find(p, v)
if a != b:
p[a] = b
groups -= 1
label = {}
for x in range(n):
label.setdefault(find(p, x), len(label))
work[0] += len(edges)
new = [(label[find(p, u)], label[find(p, v)]) for u, v in edges]
return [(a, b) for a, b in new if a != b], [label[find(p, x)] for x in range(n)]
def brute(n, edges, work):
w = {}
for u, v in edges:
w[(u, v)] = w.get((u, v), 0) + 1
best = (None, None)
for mask in range(1, 2 ** (n - 1)):
c = sum(c for (u, v), c in w.items() if (mask >> u & 1) != (mask >> v & 1))
work[0] += len(w)
if best[0] is None or c < best[0]:
best = (c, [mask >> x & 1 for x in range(n)])
return best
def karger_stein(n, edges, rng, work):
"""Returns (cut size, side bit of every vertex)."""
if n <= 6:
return brute(n, edges, work)
t = ceil(1 + n / sqrt(2))
results = []
for _ in range(2):
sub, label = contract_to(n, edges, t, rng, work)
k, side = karger_stein(t, sub, rng, work)
results.append((k, [side[label[x]] for x in range(n)]))
return min(results, key=lambda r: r[0])
def levels(n):
h = 0
while n > 6:
n, h = ceil(1 + n / sqrt(2)), h + 1
return h
def find_min_cut(n, edges, eta, method, rng):
work = [0]
if method == "karger":
trials = ceil(comb(n, 2) * log(1 / eta))
best = None
for _ in range(trials):
sub, label = contract_to(n, edges, 2, rng, work)
if best is None or len(sub) < best[0]:
best = (len(sub), label)
else:
p = 1.0
for _ in range(levels(n)):
p -= p * p / 4
trials = ceil(log(1 / eta) / p)
best = min((karger_stein(n, edges, rng, work) for _ in range(trials)), key=lambda r: r[0])
k, side = best
return k, sorted(x for x in range(n) if side[x] == side[0]), trials, work[0]
n = 14
edges = [(i, (i + 1) % n) for i in range(n) for _ in range(3 if i in (0, 7) else 4)]
rng = random.Random(203)
print("Stoer-Wagner says the minimum cut is 6, sides {0} + {8..13} vs {1..7} (cut edges (0,1) and (7,8))")
for method in ["karger", "karger-stein"]:
k, side, trials, work = find_min_cut(n, edges, 0.01, method, rng)
print(f"{method:12}: eta = 0.01 -> {trials:4} trials, work {work:7}; found cut {k}, side of vertex 0: {side}")Stoer-Wagner says the minimum cut is 6, sides {0} + {8..13} vs {1..7} (cut edges (0,1) and (7,8))
karger : eta = 0.01 -> 420 trials, work 31021; found cut 6, side of vertex 0: [0, 8, 9, 10, 11, 12, 13]
karger-stein: eta = 0.01 -> 12 trials, work 95190; found cut 6, side of vertex 0: [0, 8, 9, 10, 11, 12, 13]
Both finders return the true minimum cut and the same partition. With guarantees that hold for every graph, plain contraction needs runs, Karger-Stein only 12 trials; which is cheaper in total depends on the cost of a trial, as the next step measures.
Step 5: How the costs scale (C++)
The last step moves to C++ to reach larger graphs: heavy cycles (multiplicity 8, two opposite edges of multiplicity 7, unique minimum cut 14) with to . On these graphs a single contraction succeeds rarely (the analysis of the doubled cycle suggests a rate of order ), while Karger-Stein's per-trial rate falls only slowly. For each the program measures both rates and estimates the work to reach 99% confidence, . The generator is a fixed-seed std::mt19937, and the leaves use a weight matrix, as in Python.
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <numeric>
#include <random>
#include <utility>
#include <vector>
using Edge = std::pair<int, int>;
std::mt19937 rng(204);
long long work = 0;
int find(std::vector<int>& p, int x) { while (p[x] != x) { p[x] = p[p[x]]; x = p[x]; } return x; }
std::vector<Edge> contract_to(int n, std::vector<Edge> e, int t) {
for (int i = (int)e.size() - 1; i > 0; --i) std::swap(e[i], e[rng() % (i + 1)]);
std::vector<int> p(n);
std::iota(p.begin(), p.end(), 0);
int groups = n;
for (auto [u, v] : e) {
if (groups == t) break;
++work;
int a = find(p, u), b = find(p, v);
if (a != b) { p[a] = b; --groups; }
}
std::vector<int> label(n, -1);
int next = 0;
for (int x = 0; x < n; ++x) { int r = find(p, x); if (label[r] < 0) label[r] = next++; }
work += e.size();
std::vector<Edge> out;
for (auto [u, v] : e) {
int a = label[find(p, u)], b = label[find(p, v)];
if (a != b) out.push_back({a, b});
}
return out;
}
int brute(int n, const std::vector<Edge>& e) {
int w[6][6] = {};
for (auto [u, v] : e) ++w[std::min(u, v)][std::max(u, v)];
work += e.size();
int best = 1 << 30;
for (int mask = 1; mask < (1 << (n - 1)); ++mask) {
int c = 0;
for (int u = 0; u < n; ++u)
for (int v = u + 1; v < n; ++v)
if (((mask >> u) & 1) != ((mask >> v) & 1)) c += w[u][v];
work += n * (n - 1) / 2;
best = std::min(best, c);
}
return best;
}
int karger_stein(int n, const std::vector<Edge>& e) {
if (n <= 6) return brute(n, e);
int t = (int)std::ceil(1 + n / std::sqrt(2.0));
int a = karger_stein(t, contract_to(n, e, t));
int b = karger_stein(t, contract_to(n, e, t));
return std::min(a, b);
}
int main() {
std::printf(" n Karger rate work/run work to 99%% | KS rate work/trial work to 99%% ratio K/KS\n");
for (int n : {16, 32, 64, 128}) {
std::vector<Edge> e;
for (int i = 0; i < n; ++i)
for (int k = 0; k < ((i == 0 || i == n / 2) ? 7 : 8); ++k) e.push_back({i, (i + 1) % n});
const int target = 14, runs = 8000, trials = 24;
work = 0;
int ok = 0;
for (int r = 0; r < runs; ++r) ok += (int)contract_to(n, e, 2).size() == target;
double pk = double(ok) / runs, wk = double(work) / runs, Wk = wk * std::log(100.0) / pk;
work = 0;
int ok2 = 0;
for (int r = 0; r < trials; ++r) ok2 += karger_stein(n, e) == target;
double ps = double(ok2) / trials, ws = double(work) / trials, Ws = ws * std::log(100.0) / ps;
std::printf("%4d %11.5f %8.0f %12.3g | %7.3f %10.0f %12.3g %10.2f\n", n, pk, wk, Wk, ps, ws, Ws, Wk / Ws);
}
} n Karger rate work/run work to 99% | KS rate work/trial work to 99% ratio K/KS
16 0.01287 153 5.47e+04 | 0.875 40928 2.15e+05 0.25
32 0.00337 324 4.42e+05 | 0.625 165693 1.22e+06 0.36
64 0.00100 680 3.13e+06 | 0.583 1328074 1.05e+07 0.30
128 0.00050 1418 1.31e+07 | 0.417 5324301 5.88e+07 0.22
What the measurements show
- The bounds hold, with room to spare. Every measured single-run rate is above , and Karger-Stein's per-trial rate stays far above its guarantee.
- Rates scale as the theory says. The contraction's success falls polynomially with ; Karger-Stein's barely moves.
- Work is a different question. With an edge-list implementation on sparse graphs, one contraction run costs only , while a Karger-Stein trial costs about , mostly in its many small subproblems. At these sizes repeated contraction therefore reaches 99% confidence with three to five times less work, and the ratio in the last column shows no clear trend over this range: Karger-Stein's asymptotic advantage does not appear yet. The asymptotic comparison of the lessons ( against ) is for the adjacency-matrix model and for worst-case graphs; in practice, near-linear algorithms (Karger, 2000) or deterministic ones such as Stoer-Wagner are the tools of choice, and the contraction algorithms remain the simplest correct ones and the source of the counting results.
Extensions to try: count all distinct minimum cuts found on the plain cycle (there are , and runs find them all with high probability); stop Karger-Stein's recursion at a larger size and finish with repeated contraction; or replace edge-list contraction with an adjacency-matrix version and measure again.
Test yourself
Why does the project compare every measured cut with Stoer-Wagner?
- Stoer-Wagner is faster than both
- It is a deterministic minimum-cut algorithm, so it gives the true minimum against which each run's success is judged
- It is randomized too
- It counts the number of minimum cuts
How many plain contraction runs does the finder use for and failure target ?
- 12
What did the measurements show about the work needed for 99% confidence on sparse graphs with up to 128 vertices?
- Karger-Stein always needs less work
- Repeated contraction needed about three to five times less work, with no clear trend in the ratio yet
- Both need exactly the same work
- Karger-Stein never succeeds