P3376 【模板】网络最大流 题解 网络流入门题

题目链接:https://www.luogu.com.cn/problem/P3376

思路完全参照自 SYCstudio 的这篇博客:https://www.cnblogs.com/SYCstudio/p/7260613.html

实现代码(dinic实现):

#include <bits/stdc++.h>
using namespace std;
const int maxn = 10010, maxm = 200020, INF = (1<<29);
struct Edge {
    int u, v, w, nxt;
    Edge() {};
    Edge(int _u, int _v, int _w, int _nxt) {
        u = _u; v = _v; w = _w; nxt = _nxt;
    }
} edge[maxm];
int n, m, s, t, head[maxn], ecnt;
void init() {
    ecnt = 0;
    memset(head, -1, sizeof(int)*(n+1));
}
void addedge(int u, int v, int w) {
    edge[ecnt] = Edge(u, v, w, head[u]); head[u] = ecnt ++;
    edge[ecnt] = Edge(v, u, 0, head[v]); head[v] = ecnt ++;
}
queue<int> que;
int dep[maxn], cur[maxn];
bool bfs() {
    while (!que.empty()) que.pop();
    memset(dep, 0, sizeof(int)*(n+1));
    dep[s] = 1;
    que.push(s);
    while (!que.empty()) {
        int u = que.front();
        que.pop();
        for (int i = head[u]; i != -1; i = edge[i].nxt) {
            int v = edge[i].v, w = edge[i].w;
            if (dep[v] == 0 && w > 0) {
                dep[v] = dep[u] + 1;
                que.push(v);
            }
        }
    }
    return dep[t];
}
int dfs(int u, int flow) {
    if (u == t) return flow;
    for (int &i = cur[u]; i != -1; i = edge[i].nxt) {
        int v = edge[i].v, w = edge[i].w;
        if (dep[v] == dep[u]+1 && w > 0) {
            int f = dfs(v, min(w, flow));
            if (f > 0) {
                edge[i].w -= f;
                edge[i^1].w += f;
                return f;
            }
        }
    }
    return 0;
}
int dinic() {
    int ans = 0;
    while (bfs()) {
        for (int i = 1; i <= n; i ++) cur[i] = head[i];
        while (int d = dfs(s, INF)) ans += d;
    }
    return ans;
}
int main() {
    cin >> n >> m >> s >> t;
    init();
    while (m --) {
        int u, v, w;
        cin >> u >> v >> w;
        addedge(u, v, w);
    }
    cout << dinic() << endl;
    return 0;
}
posted @ 2020-05-17 22:20  quanjun  阅读(144)  评论(0编辑  收藏  举报