Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Graphs

Cheapest Flow First.

Max-flow finds how much you can push from a source to a sink through capacitated pipes. Min-cost max-flow adds a twist: each edge also has a per-unit cost, and among all the ways to achieve the maximum flow, you want the one that costs the least. The elegant method is a small change to max-flow: instead of augmenting along any path with spare capacity, always augment along the cheapest one — a shortest path by cost in the residual graph. Because you always send flow the cheapest available way, the running total stays minimal at every step. Push flow and watch it fill the cheapest routes first.

max flow at minimum total cost · augment along the shortest-by-cost residual path each round
capacity / cost

Each edge carries up to its capacity, charging its cost per unit of flow.

residual graph

Remaining capacity forward, plus reverse edges (with negated cost) to undo flow.

cheapest path

A shortest path from source to sink measured by total cost (Bellman-Ford/SPFA).

augment

Push as much flow as the path’s bottleneck allows, along that cheapest path.

mcmf.js — shortest augmenting path, by cost
Ready
A flow network from S to T. Each edge shows flow / capacity and its per-unit cost. Each step finds the cheapest augmenting path and pushes flow along it. Augment to push.
0
total flow
0
total cost
0
paths pushed

How it works

The correctness rests on a clean invariant: if you only ever augment along a cheapest augmenting path, then after each augmentation the current flow is the minimum-cost flow of that value. So when you finally can’t augment any more (the max flow is reached), it is automatically the minimum-cost maximum flow. Finding the cheapest path needs care because the residual graph has negative-cost reverse edges (they let you “refund” previously sent flow), so a plain Dijkstra doesn’t directly apply — you use Bellman-Ford or its SPFA optimization (or Dijkstra with Johnson-style potentials to keep it fast). Push the bottleneck amount along that path, update forward and reverse residual capacities, and repeat.

1

Build the residual graph

For each edge with capacity c and cost w, keep a forward residual (spare capacity, cost +w) and a reverse residual (0 initial capacity, cost −w) so flow can be undone.

2

Find the cheapest augmenting path

Run a shortest-path by cost from source to sink over edges with spare capacity, using Bellman-Ford / SPFA (negative reverse-edge costs rule out plain Dijkstra unless you use potentials).

3

Augment along it

Send as much flow as the path’s minimum residual capacity (its bottleneck) allows. Add the flow forward and subtract it on the reverse residual edges.

✓

Repeat until no path remains

Keep augmenting along cheapest paths until none exists. Because each augmentation was cheapest-possible, the final maximum flow has minimum total cost.

Finds
max flow, min cost
Each round
cheapest path
Path search
Bellman-Ford/SPFA
Reverse edges
cost −w

The code

# min-cost max-flow: augment along cheapest paths while True: dist, parent = spfa(source) # shortest path by COST if dist[sink] == INF: break # no augmenting path left push = min(residual[e] for e in path_to(sink)) # bottleneck for e in path_to(sink): residual[e] -= push # use capacity forward residual[reverse(e)] += push # allow undo, cost is negated max_flow += push min_cost += push * dist[sink] # cheapest path's cost per unit

Quick check

1. How does min-cost max-flow differ from plain max-flow?

2. Why can’t you use plain Dijkstra to find the cheapest augmenting path?

3. Why is the final flow guaranteed to be minimum cost?

FAQ

What is min-cost max-flow?

A network-flow problem where each edge has a capacity and a per-unit cost; the goal is maximum flow from source to sink at minimum total cost. The standard method repeatedly finds the cheapest augmenting path (shortest by cost in the residual graph) and pushes flow along it, keeping the cost minimal at every step.

Why must the cheapest path search handle negative edges?

The residual graph’s reverse edges carry negated cost (they let you cancel and re-route earlier flow), which is essential but breaks plain Dijkstra. Implementations use Bellman-Ford, SPFA, or Dijkstra with node potentials (Johnson’s technique) to handle them efficiently.

What is min-cost max-flow used for?

Transportation and logistics (ship goods at least cost), assignment and scheduling (bipartite flow), network routing with congestion costs, image segmentation, and many operations-research problems — anything shaped like "route as much as possible, as cheaply as possible, under capacities."

How does it relate to the assignment problem?

The assignment problem (match n workers to n tasks at minimum cost) is a special case: a bipartite source→workers→tasks→sink graph with unit capacities, solved by a min-cost flow of value n. The Hungarian algorithm is a faster specialized method for that case.

The picture: the network after the last augmentation

3/3 · cost 12/2 · cost 21/1 · cost 12/2 · cost 33/3 · cost 1SabTaugment 1: S, b, T2 units at cost 3 eachfinal: flow 5 (every edge full), total cost 17
The page’s network, drawn with its end state. Each edge reads flow/capacity and per-unit cost. The bold path S → b → T was the cheapest first choice (cost 3 per unit, bottleneck 2). Every edge ends full, so maximum flow is 5 and no path is left.

Worked example, step by step

The page’s network: edges S→a (capacity 3, cost 1), S→b (2, 2), a→b (1, 1), a→T (2, 3), b→T (3, 1). Each round runs SPFA over edges with spare capacity (reverse edges included, at negative cost) and then pushes the path’s bottleneck. Distances are listed in the order S, a, b, T.

StepWhat happensDetailFlowCost
Round 1 searchSPFA from Sdistances 0, 1, 2, 3; b is 2 by either S→b or S→a→b00
Round 1 pushpath S→b→Tbottleneck min(2, 3) = 2; per-unit cost 2 + 1 = 326
Round 2 searchS→b is now fulldistances 0, 1, 2, 3; b is reached through a→b26
Round 2 pushpath S→a→b→Tbottleneck min(3, 1, 1) = 1; per-unit cost 1 + 1 + 1 = 339
Round 3 searcha→b and b→T are fulldistances 0, 1, 3, 4; T only via a→T, and b is only reached backwards from T at cost −139
Round 3 pushpath S→a→Tbottleneck min(2, 2) = 2; per-unit cost 1 + 3 = 4517
Round 4 searchS→a and S→b are fullT is unreachable, so stop517

The path costs are 3, 3 and 4: they never go down, which is the signature of augmenting along cheapest paths, and it is why 2 units cost 6, 3 units cost 9 and 5 units cost 17. Each round’s bottleneck is the smallest spare capacity on its path, so three pushes move five units. Round 3 shows reverse edges in play: b is reachable only by walking back along b→T at cost −1. Here the cheapest path did not use that refund, because S→a→T was already the only way to the sink. The mistakes below use a network where it does. The final cost, 17, matches a brute-force search over every integer flow on these five edges.

Complexity and trade-offs

CaseTimeSpaceWhy
SPFA augmentationO(F · V·E) worst caseO(V + E)F is the flow value: each round pushes at least one unit. SPFA is usually far faster than its worst case, but that is data dependent. The page’s network needed 3 rounds for F = 5.
Dijkstra with potentialsO(F · E log V) after one Bellman-Ford pass for the potentialsO(V + E)Potentials keep every reduced edge cost non-negative, so Dijkstra applies. Needs a start from non-negative costs or an initial Bellman-Ford.
Max flow only (BFS paths)O(V·E²)O(V + E)Edmonds-Karp ignores costs. It reaches the same flow value but can pay more: a 4-node network below sends 2 units at cost 1 where 0 was possible.
Hungarian algorithmO(n³)O(n²)The special case of assignment (unit capacities, a bipartite graph). Faster than general min-cost flow when the problem is exactly that.
Brute force over flowsexponential in the number of edgesO(E)Fine as a test oracle on 5 edges, as used here, and useless beyond a few dozen.

The bound that matters is F, the number of augmentations, because each costs a shortest-path search. With unit pushes the page’s network needs 5 rounds, with bottleneck pushes 3. For integer capacities F is finite and the algorithm is exact; with huge capacities the dependence on F is the reason to reach for scaling methods. Dijkstra with potentials is the standard speed-up when many augmentations are expected.

Common mistakes

  • Giving the reverse edge the same cost

    The undo edge must cost −w. Take edges S→a (2, 0), S→b (2, 2), a→b (1, 1), a→T (2, 2), b→T (1, 0). The correct answer is flow 3 at cost 6, whose last path S→b→a→T walks back along a→b to refund its cost of 1. Giving that reverse edge +1 reports cost 8 for the same flow.

  • Taking any augmenting path

    Plain max-flow finds the flow value, not its cost. Take S→a (2, 0), S→b (1, 1), a→b (1, 0), a→T (1, 0), b→T (1, 0). A breadth-first search sends one unit by S→a→T and one by S→b→T: flow 2, cost 1. The cheapest-path rule sends the second unit by S→a→b→T: flow 2, cost 0.

  • Adding the path cost once instead of per unit

    The running cost is push × path_cost, not path_cost. On the page’s network that bug records 3 + 3 + 4 = 10 instead of 17, since the pushes are 2, 1 and 2 units.

  • Pushing one unit at a time

    It is correct but slow: it takes 5 augmentations on the page’s network where bottleneck pushes take 3. With capacities in the thousands, the difference is thousands of shortest-path searches.

  • Using max flow when marginal cost matters

    Min-cost max flow always pushes to the maximum, even when the last units are expensive. On the page’s network the first 3 units cost 3 each and the last 2 cost 4 each. If every unit shipped earns only 3, you want to stop at flow 3 (cost 9). Run the augmentation and stop when the path cost exceeds the value of a unit.

Where this shows up

  • Assignment and matching

    Worker-to-task or driver-to-rider matching with costs is a flow problem: a source feeds workers, each worker has one unit, each task sends one unit to the sink. Min-cost max-flow gives the cheapest complete matching.

  • Transportation and logistics

    Shipping goods from warehouses to stores over links that have both a capacity and a per-unit price is the direct form of the problem: supply, demand, link capacities and prices.

  • Scheduling with limits

    Allocating jobs to machines or time slots, where each slot has a capacity and each placement has a cost, becomes a flow network with slots as edges to the sink.

  • A building block for harder problems

    Problems such as minimum-cost path cover, or covering with at most k disjoint paths, reduce to repeated min-cost augmentation. The reverse-edge refund is what lets a late decision undo an early one.

SOLVE IT YOURSELF

Solve it: ship the most, for the least

Max-flow asks how much fits. Min-cost max-flow asks the follow-up every real system cares about: of all the ways to push that much, which is cheapest? Same residual graph — but you pick augmenting paths by price, not by whatever you find first. Python or TypeScript.

YOUR TASK

Implement MinCostMaxFlow with add_edge(u, v, cap, cost) (addEdge) and flow(s, t) returning (total_flow, total_cost). Cost is per unit shipped.

HINTS — 8 IDEAS
  1. Store each edge with a paired reverse edge of zero capacity and negated cost. Pushing flow back later must refund what it charged.
  2. Repeatedly find the cheapest source-to-sink path in the residual graph, push as much as its tightest edge allows, and repeat until no path remains.
  3. Choosing by cost rather than by arbitrary discovery is the entire difference from plain max-flow. The final flow value is identical; the bill is not.
  4. Those negative reverse costs are why you cannot just use Dijkstra here — it assumes non-negative weights. Bellman-Ford (or its SPFA queue form) handles them.
  5. The bottleneck is the smallest residual capacity along the path. Push exactly that: any more overflows an edge, any less wastes an iteration.
  6. Augmenting adds the pushed amount to each reverse edge as it subtracts from the forward one. That is what lets a later, cheaper route undo an earlier commitment.
  7. Add bottleneck × path_cost to the bill each round — not the path cost once.
  8. Because every round augments along a cheapest path, the running total is optimal at every flow value, not only at the end.
CPython · WebAssembly

Keep going

Finished this one? 0 / 99 Algorithms done
NextHungarian Algorithm: The Perfect Match Next on the “Pushing as much as it will take” ladder · rung 3 of 3

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms