dinic

const int maxn=1e5+7;
const int maxm=1e5+7;
const int inf=0x3f3f3f3f;
struct Dinic {
    struct Edge {
        int next, f, to;
    } e[maxm];
    int head[maxn], dep[maxn], tol, ans;
    int cur[maxn];
    int src, sink, n;

    void add(int u, int v, int f) {
        tol++;
        e[tol].to = v;
        e[tol].next = head[u];
        e[tol].f = f;
        head[u] = tol;
        tol++;
        e[tol].to = u;
        e[tol].next = head[v];
        e[tol].f = 0;
        head[v] = tol;
    }

    bool bfs() {
        queue<int> q;
        memset(dep, -1, sizeof(dep));
        q.push(src);
        dep[src] = 0;
        while (!q.empty()) {
            int now = q.front();
            q.pop();
            for (int i = head[now]; i; i = e[i].next) {
                if (dep[e[i].to] == -1 && e[i].f) {
                    dep[e[i].to] = dep[now] + 1;
                    if (e[i].to == sink)
                        return true;
                    q.push(e[i].to);
                }
            }
        }
        return false;
    }

    int dfs(int x, int maxx) {
        if (x == sink)
            return maxx;
        for (int &i = cur[x]; i; i = e[i].next) {
            if (dep[e[i].to] == dep[x] + 1 && e[i].f > 0) {
                int flow = dfs(e[i].to, min(maxx, e[i].f));
                if (flow) {
                    e[i].f -= flow;
                    e[i ^ 1].f += flow;
                    return flow;
                }
            }
        }
        return 0;
    }

    int dinic(int s, int t) {
        ans = 0;
        this->src = s;
        this->sink = t;
        while (bfs()) {
            for (int i = 0; i <= n; i++)
                cur[i] = head[i];
            while (int d = dfs(src, inf))
                ans += d;
        }
        return ans;
    }

    void init(int n) {
        this->n = n;
        memset(head, 0, sizeof(head));
        tol = 1;
    }
} G;

  

原文地址:https://www.cnblogs.com/Accpted/p/11191832.html