---
id: 1394
lang: en
translation_of: index.md
source_sha256: 4baf0279fa917717484e9b15abd8cac7af181458c2a92ecc15262d97f69d5857
title: "Network Flow"
description: "Notes on network flow: Dinic with the current-arc optimization, minimum cut, min-cost flow, classic models, and flows with lower and upper bounds."
tags: ["OI","Graph Theory","Bipartite Graph","Network Flow","Minimum Cut","Maximum Flow","Min-Cost Flow","Flow with Lower Bounds","Bipartite Minimum Weight Vertex Cover"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "源地 (a slip for 源点, source) rendered simply as “source”."
  - "The link text [USACO2007 OPEN]吃饭 Dining rendered as [USACO2007 OPEN] Dining, since 吃饭 (“eating, dining”) and the English name say the same thing."
  - "「网络流 24 题」 (a well-known problem set) rendered as [24 Network Flow Problems] in the LOJ6001 link text and as “the 24 Network Flow Problems” in prose, matching the English editions of posts 689 and 1000."
  - "Problem names translated: 修车 as Car Repair, 星际竞速 as Interstellar Race, NOI 美食节 as NOI Food Festival."
  - "解决方案 and 解决方法 rendered as “Solution” and “Approach” to keep the two labels distinct, as in the source."
---

## Definition

In a directed graph, there is a unique source (in-degree 0) and sink (out-degree 0), every edge has a non-negative capacity, and the whole graph is guaranteed to stay in a balanced state. Such a graph is called a network flow graph.

## Basic Network Flow Algorithms

### Maximum Flow - Dinic

The most liquid flowing through each pipe every second. The commonly used algorithm is Dinic. First run a BFS to divide the graph into levels, then use DFS to push the flow. Dinic's algorithm makes use of the residual network on the network graph to obtain the maximum flow.

One thing worth mentioning is that Dinic's algorithm has an optimization that finds the maximum flow quickly: the current-arc optimization. Before each search of the residual network, the current-arc optimization records the head pointer it has traversed to, avoiding unnecessary traversal.

<!--more-->

```cpp
bool bfs()
{
    memset(dep, 0, sizeof(dep));
    queue<int> q;
    q.push(s), dep[s] = 1;
    while (!q.empty())
    {
        int u = q.front();
        q.pop();
        for (int i = head[u]; i != -1; i = edges[i].nxt)
            if (edges[i].weight > 0 && dep[edges[i].to] == 0)
                dep[edges[i].to] = dep[u] + 1, q.push(edges[i].to);
    }
    return dep[t] != 0;
}

int dfs(int u, int flow)
{
    if (u == t || flow == 0)
        return flow;
    for (int &i = cur[u]; i != -1; i = edges[i].nxt)
        if (edges[i].weight > 0 && dep[edges[i].to] == dep[u] + 1)
        {
            int di = dfs(edges[i].to, min(flow, edges[i].weight));
            if (di > 0)
            {
                edges[i].weight -= di, edges[i ^ 1].weight += di;
                return di;
            }
        }
    return 0;
}

int dinic()
{
    int ans = 0;
    while (bfs())
    {
        memcpy(cur, head, sizeof(head));
        while (int di = dfs(s, INF))
            ans += di;
    }
    return ans;
}
```

### Minimum Cut

Deleting the set of edges with the minimum total flow so that S and T are disconnected is called the minimum cut. **The minimum cut equals the maximum flow**.

Example: [\[USACO2007 OPEN\] Dining](../566-p2891-usaco2007open-dining/index.en.html)

### Min-Cost Flow - SPFA + DFS

Concept: find the minimum cost while achieving the maximum flow. Actually, you can just use SPFA + Dinic directly: first find a shortest path, then compute the maximum flow along that path, and that guarantees the minimum cost under the maximum flow.

```cpp
bool bfs()
{
    memset(dist, 0x3f, sizeof(dist)), memset(flow, 0x3f, sizeof(flow));
    memset(vis, false, sizeof(vis)), memset(pre, -1, sizeof(pre));
    queue<int> q;
    q.push(st), dist[st] = 0, vis[st] = true;
    while (!q.empty())
    {
        int u = q.front();
        q.pop(), vis[u] = false;
        for (int i = head[u]; i != -1; i = edges[i].nxt)
            if (edges[i].weight > 0 && dist[edges[i].to] > dist[u] + edges[i].cost)
            {
                dist[edges[i].to] = dist[u] + edges[i].cost;
                pre[edges[i].to] = i, flow[edges[i].to] = min(edges[i].weight, flow[u]);
                if (!vis[edges[i].to])
                    vis[edges[i].to] = true, q.push(edges[i].to);
            }
    }
    return pre[ed] != -1;
}

long long mfmc()
{
    long long tot_cost = 0, tot_flow = 0;
    while (bfs())
    {
        tot_flow += flow[ed], tot_cost += 1LL * flow[ed] * dist[ed];
        int p = ed;
        while (p != st)
        {
            int i = pre[p];
            edges[i].weight -= flow[ed], edges[i ^ 1].weight += flow[ed];
            p = edges[i ^ 1].to;
        }
    }
    return tot_cost;
}
```

## Classic Network Flow Models

### Maximum Weight Closed Subgraph

Example (from the 24 Network Flow Problems): [https://loj.ac/problem/6001](https://loj.ac/problem/6001)

This kind of model is mainly about building a directed graph of dependencies, generally split into two parts: the positive-weight part and the negative-weight part. Usually we look for the closed subgraph with the maximum weight.

A [really good blog post](https://www.cnblogs.com/TreeDream/p/5942354.html) let me quickly understand this <span class="slang" data-zh="神仙" data-gloss="shénxiān, “immortal”. Someone, or a problem or idea, so brilliant it seems superhuman.">godlike</span> thing, so you can all go take a look. Put simply, this thing adds a source and a sink on top of the original graph, turns the vertex weights into edge weights, and then computes the minimum cut instead, that is, the maximum flow. If a positive weight is saturated, that means this plan should be dropped; if a negative weight is saturated, that means this edge should be cut in the original graph.

Solution: [LOJ6001: \[24 Network Flow Problems\] Space Flight Plan Solution](../689-libreoj-6001/index.en.html)

### The “Stacked Waiting Time” Model

Classic example: [\[SCOI2007\] Car Repair](https://www.luogu.org/problem/P2053)

First, the $n$ car owners can divide the whole timeline into $n$ time slots, and the worker in each time slot is actually different, so split them into $n * m$ vertices; the upper bound on the flow through each vertex is $1$, and the cost is just the weight multiplied by the current position in the order.

Another similar problem is NOI's Food Festival.

### Bipartite Minimum Weight Vertex Cover

Example: [POJ 2125](http://poj.org/problem?id=2125)

Consider splitting each vertex into two: an in-vertex and an out-vertex. After separating the in-vertex and the out-vertex, connect the source with weight $w_-$, and connect the sink with weight $w_+$. When an edge is saturated, it means the in-vertex in the middle was passed through, and vice versa, and that is enough to get this problem done.

```cpp
// POJ2125.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>

const int MAX_N = 2e5 + 200, INF = 0x3f3f3f3f;

using namespace std;

int n, m, head[MAX_N], current, dep[MAX_N], cur[MAX_N], st, ed;
bool mark[MAX_N];

struct edge
{
    int to, nxt, flow;
} edges[MAX_N << 1];

void addpath(int src, int dst, int weight)
{
    edges[current].to = dst, edges[current].nxt = head[src];
    edges[current].flow = weight, head[src] = current++;
}

void addtube(int src, int dst, int flow)
{
    addpath(src, dst, flow);
    addpath(dst, src, 0);
}

bool bfs()
{
    memset(dep, 0, sizeof(dep));
    dep[st] = 1;
    queue<int> q;
    q.push(st);
    while (!q.empty())
    {
        int u = q.front();
        q.pop();
        for (int i = head[u]; i != -1; i = edges[i].nxt)
            if (edges[i].flow > 0 && dep[edges[i].to] == 0)
                dep[edges[i].to] = dep[u] + 1, q.push(edges[i].to);
    }
    return dep[ed] != 0;
}

int dfs(int u, int flw)
{
    if (u == ed || flw == 0)
        return flw;
    for (int &i = cur[u]; i != -1; i = edges[i].nxt)
        if (edges[i].flow > 0 && dep[edges[i].to] == dep[u] + 1)
        {
            int di = dfs(edges[i].to, min(flw, edges[i].flow));
            if (di > 0)
            {
                edges[i].flow -= di, edges[i ^ 1].flow += di;
                return di;
            }
        }
    return 0;
}

int dinic()
{
    int ans = 0;
    while (bfs())
    {
        memcpy(cur, head, sizeof(head));
        while (int di = dfs(st, INF))
            ans += di;
    }
    return ans;
}

void dfs_helper(int u)
{
    mark[u] = true;
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (edges[i].flow > 0 && !mark[edges[i].to])
            dfs_helper(edges[i].to);
}

int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d%d", &n, &m), st = (n << 1) | 1, ed = st + 1;
    for (int i = 1, tmpy; i <= n; i++)
        scanf("%d", &tmpy), addtube(i + n, ed, tmpy);
    for (int i = 1, tmpx; i <= n; i++)
        scanf("%d", &tmpx), addtube(st, i, tmpx);
    for (int i = 1, tmpx, tmpy; i <= m; i++)
        scanf("%d%d", &tmpx, &tmpy), addtube(tmpx, tmpy + n, INF);
    printf("%d\n", dinic());
    dfs_helper(st);
    int ans = 0;
    for (int i = 1; i <= n; i++)
        if (!mark[i])
            ans++;
    for (int i = n + 1; i <= 2 * n; i++)
        if (mark[i])
            ans++;
    printf("%d\n", ans);
    for (int i = 1; i <= n; i++)
        if (!mark[i])
            printf("%d -\n", i);
    for (int i = n + 1; i <= 2 * n; i++)
        if (mark[i])
            printf("%d +\n", i - n);
    return 0;
}
```

There is another similar problem, though weighted, that uses the same idea: [P2469 \[SDOI2010\] Interstellar Race](https://www.luogu.com.cn/problem/P2469). Do a cover on the bipartite graph, then compute the minimum cost.

## Network Flow with Lower and Upper Bounds

### Feasible Flow with Lower and Upper Bounds, No Source or Sink

**Problem Statement**

> Given a network, the flow on every edge must lie in the interval $[lower[e_x], upper[e_x]]$. Find a feasible flow.

**Solution**

Consider simplifying the interval of each edge into $[0, upper[e_x] - lower[e_x]]$, and it becomes a normal network flow model. However, because the lower and upper bounds differ from edge to edge, computing the maximum flow directly can lead to this situation: after some edges are saturated, the lower bounds of some edges are not low enough, so the result does not match the problem. So we need to maintain an array $di[u]$, representing the flow that needs to be supplied or released, and so we know:

$$
di_u = \sum_{e = E(?, u)} e.flow - \sum_{e = E(u, ?)} e.flow
$$

For the case $di_u > 0$, consider connecting the super source $S$ to $u$ to supply the needed flow; for the case $di_u < 0$, consider connecting vertex $u$ to the super sink to release the excess flow. So it can obviously be solved.

### Feasible Flow with Lower and Upper Bounds, with a Source

**Problem Statement**

> Given a network, the flow on every edge must lie in the interval $[lower[e_x], upper[e_x]]$, and given the source and sink $s$ and $t$, the flow into the source equals the flow out of the sink. Find a feasible flow.

**Approach**

Add an edge: from $t$ to $s$, with range $[0, +\infty]$, and that is it.

**Note**  What the problem really means is just to ignore the “balance of income and expenditure” between $s$ and $t$. So just connect such an edge directly and you are done.
