TExcelTAD
Home › Selected Topics: FFT, Strings, Parallelism & NP-Completeness › Shortest Paths and Flows as Linear Programs

Shortest Paths and Flows as Linear Programs

The graph algorithms of Graph Algorithms are fast and specialized. Linear programming is slower but general, and writing those same problems as LPs teaches two things: how to turn a combinatorial question into variables and constraints, and why some of these LPs have integer optimal solutions for free. This lesson formulates single-pair shortest paths, maximum flow and minimum-cost flow as LPs, solves them with SciPy and checks each answer against a combinatorial algorithm.

Shortest paths: a maximization

Let G=(V,E)G = (V, E) be a directed graph with edge weights w(u,v)w(u, v), a source ss and a target tt. Give every vertex a variable dvd_v and write

maximizedtsubject todv≤du+w(u,v)for every edge (u,v)∈E,ds=0.\begin{aligned} \text{maximize} \quad & d_t \\ \text{subject to} \quad & d_v \le d_u + w(u, v) && \text{for every edge } (u, v) \in E, \\ & d_s = 0 . \end{aligned}

The constraints are the triangle inequalities that the true distances δ(s,v)\delta(s, v) satisfy (Relaxation). It may seem odd that a shortest path is a maximization, but the constraints only bound dvd_v from above: along any path s=v0,v1,…,vk=ts = v_0, v_1, \ldots, v_k = t they add up to dt≤∑iw(vi−1,vi)d_t \le \sum_i w(v_{i-1}, v_i), so dtd_t is at most the length of every path, and the largest value it can take is the shortest length. Minimizing would just send every dvd_v to −∞-\infty. These are the same difference constraints as in Difference Constraints and Shortest Paths, read in the other direction.

python · try it yourself
from scipy.optimize import linprog

V = ["s", "a", "b", "c", "t"]
E = [("s", "a", 4), ("s", "b", 1), ("b", "a", 2), ("a", "c", 1), ("b", "c", 5), ("c", "t", 3), ("a", "t", 6)]
idx = {v: i for i, v in enumerate(V)}

A_ub, b_ub = [], []
for u, v, w in E:                                # d_v - d_u <= w
    row = [0] * len(V); row[idx[v]] = 1; row[idx[u]] = -1
    A_ub.append(row); b_ub.append(w)
A_eq, b_eq = [[1 if v == "s" else 0 for v in V]], [0]
c = [-1 if v == "t" else 0 for v in V]           # maximize d_t = minimize -d_t
res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=[(None, None)] * len(V), method="highs")
print("LP value d_t =", round(-res.fun, 6))

dist = {v: float("inf") for v in V}; dist["s"] = 0
for _ in range(len(V) - 1):                      # Bellman-Ford as the referee
    for u, v, w in E:
        dist[v] = min(dist[v], dist[u] + w)
print("Bellman-Ford distances:", dist)
tight = [(u, v) for u, v, w in E if dist[v] == dist[u] + w]
print("tight edges (where the constraint holds with equality):", tight)
LP value d_t = 7.0
Bellman-Ford distances: {'s': 0, 'a': 3, 'b': 1, 'c': 4, 't': 7}
tight edges (where the constraint holds with equality): [('s', 'b'), ('b', 'a'), ('a', 'c'), ('c', 't')]

The tight edges contain the shortest path s→b→a→c→ts \to b \to a \to c \to t of length 7. (The LP's other variables are not unique: any dvd_v below its distance that keeps the constraints is allowed, because only dtd_t is maximized.)

Maximum flow

A flow network has capacities c(u,v)≥0c(u, v) \ge 0 on its edges, a source ss and a sink tt (Flow Networks). With one variable fuvf_{uv} per edge, the maximum flow problem is

maximize∑(s,v)∈Efsv−∑(v,s)∈Efvssubject to0≤fuv≤c(u,v)for every edge (capacity),∑(u,v)∈Efuv=∑(v,w)∈Efvwfor every v≠s,t (conservation).\begin{aligned} \text{maximize} \quad & \sum_{(s, v) \in E} f_{sv} - \sum_{(v, s) \in E} f_{vs} \\ \text{subject to} \quad & 0 \le f_{uv} \le c(u, v) && \text{for every edge (capacity)}, \\ & \sum_{(u, v) \in E} f_{uv} = \sum_{(v, w) \in E} f_{vw} && \text{for every } v \ne s, t \text{ (conservation)}. \end{aligned}

The LP has ∣E∣\lvert E \rvert variables and ∣V∣−2\lvert V \rvert - 2 equations plus the bounds. The program solves it and compares with a short Edmonds-Karp implementation.

python · try it yourself
from collections import deque
from scipy.optimize import linprog

V = ["s", "a", "b", "c", "d", "t"]
E = [("s", "a", 10), ("s", "b", 8), ("a", "b", 2), ("a", "c", 5), ("b", "d", 10),
     ("c", "t", 7), ("d", "c", 4), ("d", "t", 6)]

c = [-1 if u == "s" else 0 for u, v, cap in E]   # maximize the flow out of s
A_eq = [[(1 if v == x else 0) - (1 if u == x else 0) for u, v, cap in E] for x in V if x not in "st"]
res = linprog(c, A_eq=A_eq, b_eq=[0] * len(A_eq), bounds=[(0, cap) for u, v, cap in E], method="highs")
print("LP max flow:", round(-res.fun, 6))
print("every edge flow of the LP vertex is an integer:", all(abs(f - round(f)) < 1e-9 for f in res.x))

def edmonds_karp(V, E, s, t):
    r = {}
    for u, v, cap in E:
        r[(u, v)] = r.get((u, v), 0) + cap
        r.setdefault((v, u), 0)
    total = 0
    while True:
        parent, q = {s: None}, deque([s])
        while q and t not in parent:
            u = q.popleft()
            for x in V:
                if x not in parent and r.get((u, x), 0) > 0:
                    parent[x] = u; q.append(x)
        if t not in parent:
            return total
        path, x = [], t
        while parent[x] is not None:
            path.append((parent[x], x)); x = parent[x]
        b = min(r[e] for e in path)
        for u, v in path:
            r[(u, v)] -= b; r[(v, u)] += b
        total += b

print("Edmonds-Karp:", edmonds_karp(V, E, "s", "t"))
LP max flow: 13.0
every edge flow of the LP vertex is an integer: True
Edmonds-Karp: 13

Both find 13. The solver returns a vertex of the feasible polytope, and that vertex is integral although nothing in the LP asked for integers. (Several flows reach 13 here, so the solver may pick any of them; all its vertices are integral.)

Why the answers come out integral

The constraint matrix of the flow LP is the incidence matrix of the directed graph: every column (edge) has one +1+1 and one −1-1. Such matrices are totally unimodular: every square submatrix has determinant 00, 11 or −1-1. By Cramer's rule, every vertex of {x:Ax=b, 0≤x≤c}\{x : Ax = b,\ 0 \le x \le c\} is then integral whenever bb and cc are integral. That is the LP explanation of the integrality theorem for flows, and the reason why LP methods solve bipartite matching and many scheduling problems exactly. The shortest-path LP's matrix is the transpose of an incidence matrix, also totally unimodular, so its vertex solutions are integral for integer weights.

Minimum-cost flow

Now each edge also has a cost a(u,v)a(u, v) per unit of flow, and the task is to send exactly DD units from ss to tt as cheaply as possible:

minimize∑(u,v)∈Ea(u,v) fuvsubject to0≤fuv≤c(u,v),conservation at every v≠s,t,∑vfsv−∑vfvs=D.\begin{aligned} \text{minimize} \quad & \sum_{(u, v) \in E} a(u, v)\, f_{uv} \\ \text{subject to} \quad & 0 \le f_{uv} \le c(u, v), \\ & \text{conservation at every } v \ne s, t, \\ & \textstyle\sum_v f_{sv} - \sum_v f_{vs} = D . \end{aligned}

Min-cost flow generalizes both earlier problems: shortest paths are min-cost flows of one unit with unlimited capacities, and maximum flow is a min-cost flow with cost −1-1 on an extra edge from tt back to ss. It has fast combinatorial algorithms too, but the LP is a one-liner to write down.

python · try it yourself
from scipy.optimize import linprog

V = ["s", "a", "b", "t"]
E = [("s", "a", 4, 2), ("s", "b", 2, 2), ("a", "b", 2, 1), ("a", "t", 3, 3), ("b", "t", 5, 1)]   # (u, v, capacity, cost)
D = 5
A_eq = [[(1 if v == x else 0) - (1 if u == x else 0) for u, v, cap, cost in E] for x in V if x not in "st"]
A_eq.append([(1 if u == "s" else 0) - (1 if v == "s" else 0) for u, v, cap, cost in E])
b_eq = [0] * (len(V) - 2) + [D]
res = linprog([cost for *_, cost in E], A_eq=A_eq, b_eq=b_eq,
              bounds=[(0, cap) for u, v, cap, cost in E], method="highs")
print("minimum cost of sending", D, "units:", round(res.fun, 6))
for (u, v, cap, cost), f in zip(E, res.x):
    print(f"  {u}->{v}: {round(f, 6)} of {cap} at cost {cost} each")
minimum cost of sending 5 units: 19.0
  s->a: 3.0 of 4 at cost 2 each
  s->b: 2.0 of 2 at cost 2 each
  a->b: 2.0 of 2 at cost 1 each
  a->t: 1.0 of 3 at cost 3 each
  b->t: 4.0 of 5 at cost 1 each

The cheap route s→b→ts \to b \to t (cost 3 per unit) is saturated at its first edge's capacity 2; the next cheapest, s→a→b→ts \to a \to b \to t (cost 4 per unit), takes 2 more until edge a→ba \to b is full; the last unit uses s→a→ts \to a \to t at cost 5. Total 6+8+5=196 + 8 + 5 = 19.

Problems only LP solves in polynomial time

Some flow problems have no known polynomial algorithm other than linear programming. In multicommodity flow, several pairs (si,ti)(s_i, t_i) each need DiD_i units of their own commodity through shared capacities. The LP has one variable per commodity per edge and adds the capacity constraint ∑ifuvi≤c(u,v)\sum_i f^i_{uv} \le c(u, v). The matrix is no longer totally unimodular, so integer solutions are not guaranteed (and finding integral multicommodity flows is NP-hard), but the fractional problem is solved in polynomial time by LP. Duality, the deeper reason why max flow equals min cut and why shortest-path LPs have the shape they do, is developed in Linear Programming & Duality for Algorithms and in LP Duality.

In C++

A certificate check in C++: given Bellman-Ford distances, verify that they satisfy every LP constraint (feasibility) and that the target's value is achieved by a path of tight edges (so no feasible dtd_t can be larger). Together that proves optimality without any LP solver.

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

struct Edge { int u, v, w; };

int main() {
    const char* name = "sabct";
    std::vector<Edge> E = {{0, 1, 4}, {0, 2, 1}, {2, 1, 2}, {1, 3, 1}, {2, 3, 5}, {3, 4, 3}, {1, 4, 6}};
    const int n = 5, INF = 1 << 29;
    std::vector<int> d(n, INF), parent(n, -1);
    d[0] = 0;
    for (int round = 0; round < n - 1; round++)
        for (auto [u, v, w] : E)
            if (d[u] + w < d[v]) { d[v] = d[u] + w; parent[v] = u; }
    bool feasible = true;
    for (auto [u, v, w] : E) feasible = feasible && d[v] <= d[u] + w;
    std::printf("all %zu constraints d_v <= d_u + w hold: %s\n", E.size(), feasible ? "yes" : "no");
    std::printf("tight path to t:");
    std::vector<int> path;
    for (int x = 4; x != -1; x = parent[x]) path.insert(path.begin(), x);
    for (int x : path) std::printf(" %c", name[x]);
    std::printf(", length %d = d_t\n", d[4]);
}
all 7 constraints d_v <= d_u + w hold: yes
tight path to t: s b a c t, length 7 = d_t

Test yourself

Why is the single-pair shortest-path LP a maximization of dtd_t?

  1. Because the weights are negative
  2. Because the constraints dv≤du+w(u,v)d_v \le d_u + w(u, v) only bound dtd_t from above by every path length, so its largest feasible value is the shortest length
  3. Because LPs must maximize
  4. Because the minimum is always 0

What do the conservation constraints of the max-flow LP say?

  1. Every edge carries at most its capacity
  2. At every vertex other than ss and tt, the flow in equals the flow out
  3. The flow out of ss equals its capacity
  4. All flows are integers

Why does the max-flow LP have integral optimal vertices when the capacities are integers?

  1. Because the solver rounds
  2. Because its constraint matrix (an incidence matrix) is totally unimodular
  3. Because flows are always integers
  4. Because the graph is acyclic

Which problem is known to be solvable in polynomial time mainly through linear programming?

  1. Single-source shortest paths
  2. Maximum flow
  3. Fractional multicommodity flow
  4. Minimum spanning tree