网络流--最大流--EK模板

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
#define INF 0x3f3f3f3f
using namespace std;
int n,m;
const int maxn=1005;
int g[maxn][maxn];//容量
int f[maxn][maxn];//流量
bool vis[maxn];
int pre[maxn];
bool bfs(int s,int t){
    memset(pre,-1,sizeof pre);
    memset(vis,false,sizeof vis);
    queue<int> q;
    vis[s]=true;
    q.push(s);
    while(!q.empty()){
        int now=q.front();
        q.pop();
        for(int i=1;i<=n;i++){
            if(!vis[i]&&g[now][i]){
                vis[i]=true;
                pre[i]=now;
                if(i==t) return true; //找到汇点,即找到增广路。
                q.push(i);
            }
        }
    }
    return false;
}
int EK(int s,int t){
    int maxflow=0;
    int u,v;
    while(bfs(s,t)){
        int d=INF;
        v=t;
        while(v!=s){
            u=pre[v];
            if(d>g[u][v])
                d=g[u][v];
            v=u;
        }
        maxflow+=d;
        v=t;
        while(v!=s){
            u=pre[v];
            g[u][v]-=d;
            g[v][u]+=d;
            if(f[v][u]>0)
                f[v][u]-=d;
            else f[u][v]+=d;
            v=u;
        }
    }
    return maxflow;
}
int main()
{
    //int s,t;
    int u,v,c;
    while(~scanf("%d%d",&m,&n)){
        memset(f,0,sizeof f);
        memset(g,0,sizeof g);
        for(int i=1;i<=m;i++){
            scanf("%d%d%d",&u,&v,&c);
            g[u][v]+=c;
        }
        printf("%d
",EK(1,n));
    }
    return 0;
}
原文地址:https://www.cnblogs.com/lunatic-talent/p/12798639.html