Min Cost Flow
Solves minimum cost (b-)flow problem.
As of 2025/12/31, this implementation is the fastest in Python3 (PyPy).
__init__
Arguments
n: int: number of nodes
add_supply
Adds a supply of amount units to a node if amount > 0 or a demand of -amount units if amount < 0.
Arguments
v: int: nodeamount: int: amount of supply
add_edge
Appends an edge with capacity to the graph.
Arguments
u: int: from nodev: int: to nodelower: int: lower bound of flowupper: int: upper bound of flowcost: int: cost of flow
solve
Finds the minimum cost of the b-flow.
Returns
int | None: the minimum cost of the b-flow if the b-flow is feasible,Noneotherwise
Complexities
where represents the number of edges and supplies added, and represents the maximum capacity (upper - lower) of the edges.
edges
Returns the edges of the graph with flow that achieves the minimum cost.
Note: you must call solve before using this method.
Returns
list[tuple[int, int, int]]: list of edges with flow that achieves the minimum cost- Each element
(u, v, flow)represents an edge from nodeuto nodevwith flowflow.
- Each element
