[模板]洛谷P3376 最大流(dinic)

#include<bits/stdc++.h>
#define ll long long
#define PB push_back
#define endl '\n'
#define INF 0x3f3f3f3f
#define LINF 0x3f3f3f3f3f3f3f3f
#define ull unsigned long long
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define lowbit(x) (x & (-x))
#define rep(i, a, b) for(int i = a ; i <= b ; ++ i)
#define per(i, a, b) for(int i = b ; i >= a ; -- i)
#define clr(a, b) memset(a, b, sizeof(a))
#define in insert
#define random(x) (rand()%x)
#define PII(x, y) make_pair(x, y)
#define fi first
#define se second
#define pi acos(-1)
using namespace std;
const int maxn = 2e6 + 1000;
const ll mod = 998244353;
const int M = 5000 + 10;
const int N = 200 + 10;
int n, m, s, t, cnt;
int head[N], vis, inq[N], cur[N];
int dis[N];
ll maxflow, cost;
struct node{
    int to, next;
    ll flow;
}edge[M<<1];
void add(int u, int v, ll flow){
    edge[cnt].to = v;
    edge[cnt].flow = flow;
    edge[cnt].next = head[u];
    head[u] = cnt ++;
}
bool spfa(){
    rep(i, 1, n) dis[i] = 1e9, inq[i] = 0, cur[i] = head[i];
    queue<int> que; dis[s] = 0;
    inq[s] = 1; que.push(s);
    while(!que.empty()){
        int u = que.front();
        que.pop();
        inq[u] = 0;
        for(int i = head[u] ; ~ i ; i = edge[i].next){
            int v = edge[i].to;
            if(dis[v] > dis[u] + 1 && edge[i].flow){
                dis[v] = dis[u] + 1;
                if(!inq[v]){
                    inq[v] = 1;
                    que.push(v);
                }
            }
        }
    }
    return dis[t] == 1e9 ? 0 : 1;
}
int dfs(int u, ll flow){
    if(u == t){
        vis = 1;
        maxflow += flow;
        return flow;
    }
    ll used = 0;
    for(int i = cur[u] ; ~ i ; i = edge[i].next){
        int v = edge[i].to;
        cur[u] = i;
        if(edge[i].flow && dis[v] == dis[u] + 1){
            ll minflow = dfs(v, min(flow - used, edge[i].flow));
            if(minflow){

                edge[i].flow -= minflow;
                edge[i^1].flow += minflow;
                used += minflow;
            }
            if(used == flow) break;
        }
    }
    return used;
}
void dinic(){
    while(spfa()){
        vis = 1;
        while(vis){
            vis = 0;
            dfs(s, 1e9); 
        }
    }
}
signed main(){
    ll u, v, w, z; int q;
    scanf("%d %d %d %d", &n, &m, &s, &t);
    clr(head, -1);
    maxflow = cost = 0;
    cnt = 0;
    while(m --){
        scanf("%lld %lld %lld", &u, &v, &w);
        add(u, v, w);
        add(v, u, 0);
    }
    dinic();
    cout << maxflow;
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/Ketchum/p/13294932.html