Primal-Dual for Steiner Forest
The Steiner forest problem (also called the generalized Steiner tree problem): given a graph with edge costs and pairs of terminals , find a cheapest set of edges in which each is connected to its . Different pairs may share edges or live in different components. With a single pair it is shortest path; with all pairs drawn from one terminal set it is Steiner tree (Steiner Trees and the Metric Closure). The MST trick does not apply, because the algorithm does not know which terminals should end up together. Agrawal, Klein and Ravi (1995) and Goemans and Williamson (1995) solved it with a primal-dual algorithm of ratio , where is the number of terminals. Goemans and Williamson's version became a general framework for network design.
A cut LP with exponentially many constraints
Call a vertex set separating if some pair has exactly one terminal in ; then any solution must contain an edge of the cut . Let be the separating sets.
The primal has one constraint per cut, exponentially many. The dual has one variable per cut, a "moat" around of width : an edge crossing several moats must be at least as long as their total width. The primal-dual algorithm will raise only polynomially many of these variables.
The algorithm
PRIMAL-DUAL-STEINER-FOREST(G, c, pairs)
1 F = empty; every vertex is its own component; all y_S = 0
2 while some component C is active -- C separates some pair
3 raise y_C uniformly, at the same speed, for every active component C,
4 until some edge e between two components becomes tight
5 (the total width of the moats it crosses reaches c_e)
6 add e to F, merging the two components
7 reverse delete: for each edge of F in reverse order of addition,
8 remove it if all pairs remain connected without it
9 return F and yThe moats grow like ripples. A component stops growing ("becomes inactive") once it contains both terminals of every pair it touches. Each step merges two components, so there are at most events, and each event can be found in polynomial time by computing, for every edge, how long until it becomes tight.
Theorem (Agrawal, Klein and Ravi, 1995; Goemans and Williamson, 1995). The algorithm returns a feasible Steiner forest and a feasible dual with .
Proof sketch. Feasibility of the dual: an edge stops being raised the moment it becomes tight. Feasibility of : the algorithm runs until no component separates a pair, and reverse delete only removes edges that are not needed. Every edge of is tight, so
where counts the edges of leaving . It suffices to show that in every phase of uniform growth, the active components satisfy : then each unit of time adds at most to the left side and exactly to the dual. For this, contract each current component to a node; the edges of between them form a forest. In a forest the average degree is less than 2. Reverse delete guarantees that no inactive node is a leaf (an inactive leaf's only edge would not be needed for any pair, and reverse delete would have removed it), so the inactive nodes only raise the average, and the active nodes alone have average degree at most 2. A finer count gives .
Without reverse delete the bound fails: the growth phase may add edges that serve no pair.
from fractions import Fraction as F
from itertools import combinations
def connected(n, edges, a, b):
adj = {v: [] for v in range(n)}
for u, v, _ in edges:
adj[u].append(v); adj[v].append(u)
seen, stack = {a}, [a]
while stack:
for v in adj[stack.pop()]:
if v not in seen:
seen.add(v); stack.append(v)
return b in seen
def primal_dual(n, E, pairs):
comp = list(range(n))
load = {i: F(0) for i in range(len(E))} # total moat width crossed by each edge
active = lambda c: any((comp[s] == c) != (comp[t] == c) for s, t in pairs)
F_edges, dual = [], F(0)
while any(active(c) for c in set(comp)):
best = None
for i, (u, v, c) in enumerate(E):
if comp[u] != comp[v]:
rate = active(comp[u]) + active(comp[v])
if rate:
t = (c - load[i]) / rate
if best is None or t < best[0]:
best = (t, i)
t, i = best
n_active = sum(active(c) for c in set(comp))
dual += t * n_active
for j, (u, v, c) in enumerate(E): # every edge between components grows
if comp[u] != comp[v]:
load[j] += t * (active(comp[u]) + active(comp[v]))
u, v, _ = E[i]
F_edges.append(E[i])
old, new = comp[v], comp[u]
comp = [new if x == old else x for x in comp]
grown = len(F_edges)
for e in reversed(list(F_edges)): # reverse delete
rest = [f for f in F_edges if f != e]
if all(connected(n, rest, s, t) for s, t in pairs):
F_edges = rest
return F_edges, dual, grown
def optimum(n, E, pairs):
best = None
for k in range(len(E) + 1):
for S in combinations(E, k):
cost = sum(c for _, _, c in S)
if (best is None or cost < best) and all(connected(n, S, s, t) for s, t in pairs):
best = cost
return best
n = 8
E = [(0, 3, 1), (0, 4, 5), (0, 7, 2), (1, 2, 9), (1, 5, 5), (1, 7, 7), (2, 3, 8), (2, 6, 1), (3, 5, 6), (3, 7, 2), (4, 6, 9), (5, 7, 7)]
pairs = [(2, 1), (7, 4), (0, 5)]
Fe, dual, grown = primal_dual(n, E, pairs)
alg = sum(c for _, _, c in Fe)
print("edges added while growing:", grown, " kept after reverse delete:", [(u, v) for u, v, _ in Fe])
print("dual value", dual, " ALG", alg, " OPT", optimum(n, E, pairs), " ALG <= 2 * dual:", alg <= 2 * dual)edges added while growing: 7 kept after reverse delete: [(0, 7), (0, 4), (1, 5), (1, 7), (1, 2)]
dual value 37/2 ALG 28 OPT 23 ALG <= 2 * dual: True
The growth phase added seven edges and reverse delete removed two that no pair needed. The forest costs 28 against an optimum of 23, and the moats certify this without knowing OPT: their total width is a lower bound, so the forest is provably within of optimal.
In C++
The growth phase with floating-point event times (with integer costs every event time is a dyadic fraction, so the values here are exact in binary), followed by reverse delete with a union-find connectivity check.
#include <cstdio>
#include <numeric>
#include <vector>
struct Edge { int u, v; double c; };
int n = 8;
std::vector<Edge> E = {{0, 3, 1}, {0, 4, 5}, {0, 7, 2}, {1, 2, 9}, {1, 5, 5}, {1, 7, 7}, {2, 3, 8}, {2, 6, 1}, {3, 5, 6}, {3, 7, 2}, {4, 6, 9}, {5, 7, 7}};
std::vector<std::pair<int, int>> pairs = {{2, 1}, {7, 4}, {0, 5}};
int find(std::vector<int>& p, int x) { return p[x] == x ? x : p[x] = find(p, p[x]); }
bool feasible(const std::vector<int>& chosen) {
std::vector<int> p(n);
std::iota(p.begin(), p.end(), 0);
for (int i : chosen) p[find(p, E[i].u)] = find(p, E[i].v);
for (auto [s, t] : pairs) if (find(p, s) != find(p, t)) return false;
return true;
}
int main() {
std::vector<int> comp(n);
std::iota(comp.begin(), comp.end(), 0);
auto active = [&](int c) {
for (auto [s, t] : pairs) if ((comp[s] == c) != (comp[t] == c)) return 1;
return 0;
};
std::vector<double> load(E.size(), 0);
std::vector<int> F;
double dual = 0;
while (true) {
int nActive = 0;
std::vector<bool> seen(n, false);
for (int v = 0; v < n; v++) if (!seen[comp[v]]) { seen[comp[v]] = true; nActive += active(comp[v]); }
if (!nActive) break;
int best = -1;
double bt = 0;
for (size_t i = 0; i < E.size(); i++) {
int cu = comp[E[i].u], cv = comp[E[i].v];
int rate = cu != cv ? active(cu) + active(cv) : 0;
if (rate && (best < 0 || (E[i].c - load[i]) / rate < bt)) { best = i; bt = (E[i].c - load[i]) / rate; }
}
dual += bt * nActive;
for (size_t i = 0; i < E.size(); i++) {
int cu = comp[E[i].u], cv = comp[E[i].v];
if (cu != cv) load[i] += bt * (active(cu) + active(cv));
}
F.push_back(best);
int from = comp[E[best].v], to = comp[E[best].u];
for (int& c : comp) if (c == from) c = to;
}
for (int k = (int)F.size() - 1; k >= 0; k--) {
std::vector<int> rest = F;
rest.erase(rest.begin() + k);
if (feasible(rest)) F = rest;
}
double cost = 0;
std::printf("forest:");
for (int i : F) { std::printf(" (%d,%d)", E[i].u, E[i].v); cost += E[i].c; }
std::printf("\ncost %.1f, dual %.1f, ratio to dual %.3f\n", cost, dual, cost / dual);
}forest: (0,7) (0,4) (1,5) (1,7) (1,2)
cost 28.0, dual 18.5, ratio to dual 1.514
The general framework
Goemans and Williamson phrased the algorithm for any covering problem of the form "for every set with , pick an edge of ", where is a proper function: symmetric () and disjoint-maximal ( for disjoint ). The same moat growing and reverse delete give factor 2 for all of them. Examples beyond Steiner forest:
- Steiner tree and MST ( when separates terminals).
- -joins and minimum-weight perfect matching in metric graphs (factor 2, much faster than exact matching).
- Prize-collecting Steiner tree (a terminal may be left out by paying a penalty): factor with a variant of the algorithm, improved to about 1.97 by Archer, Bateni, Hajiaghayi and Karloff (2011) and further since.
For survivable network design, where pair needs edge-disjoint paths, the cut constraints become , and the primal-dual method only gives a factor of order . Jain (2001) obtained factor 2 by iterative rounding: every extreme point of the LP has an edge with ; round it up and re-solve.
Steiner forest and Steiner tree are APX-hard, so a PTAS is ruled out unless P = NP. Whether Steiner forest has a ratio below 2 is a well-known open question. The cut LP cannot help: on a cycle of vertices that are all terminals, on every edge is feasible with value , while every solution needs edges, an integrality gap of . Improving 2 would need a different relaxation.
The program checks the gap on a 6-cycle with unit costs, writing down the cut LP with all proper vertex sets as constraints (every proper subset separates two terminals here) and solving it.
from itertools import combinations
from scipy.optimize import linprog
n = 6
edges = [(i, (i + 1) % n) for i in range(n)]
rows = []
for k in range(1, n):
for S in combinations(range(n), k):
S = set(S)
rows.append([-1 if (u in S) != (v in S) else 0 for u, v in edges]) # edges crossing the cut
res = linprog([1] * len(edges), A_ub=rows, b_ub=[-1] * len(rows), bounds=[(0, None)] * len(edges), method="highs")
print(f"{len(rows)} cut constraints, LP value {float(res.fun):.3f} with x = {[round(float(x), 3) for x in res.x]}")
print(f"optimal Steiner tree: {n - 1} edges, gap {(n - 1) / float(res.fun):.3f} = 2 - 2/n")62 cut constraints, LP value 3.000 with x = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5]
optimal Steiner tree: 5 edges, gap 1.667 = 2 - 2/n
Test yourself
Which components grow their moats in the primal-dual algorithm?
- All components
- The active ones: components that separate some terminal pair
- Only components containing two terminals
- Only single vertices
What is the role of the reverse delete step?
- It makes the dual feasible
- It removes unnecessary edges so that no inactive component is a leaf of the contracted forest, which gives the average-degree bound behind the factor 2
- It speeds up the algorithm
- It is optional and does not affect the guarantee
Why does the algorithm handle an LP with exponentially many constraints?
- It solves the LP by the ellipsoid method
- It never writes the LP down: it raises dual variables only for current components, at most polynomially many in total
- It approximates the LP by sampling
- Because the cuts are few in planar graphs