洛谷 P3376 【模板】网络最大流

讲解:

https://www.luogu.org/blog/ONE-PIECE/wang-lao-liu-di-zong-jie

模板:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;

const int maxn=100010;
const int INF=1<<30;

struct Edge {
    int v,w,nxt;
};

struct Node {
    int u,ecnt;
};

int head[maxn];
Edge edge[2*maxn];
Node pre[maxn];
bool vis[maxn];

int ecnt,n,m,s,t;

void init()
{
    ecnt=0;
    memset(edge,0,sizeof(edge));
    memset(head,-1,sizeof(head));
}

void addEdge(int u,int v,int w)
{
    edge[ecnt].v=v;
    edge[ecnt].w=w;
    edge[ecnt].nxt=head[u];
    head[u]=ecnt++;
}

bool bfs()
{
    memset(vis,0,sizeof(vis));
    memset(pre,-1,sizeof(pre));
    queue<int> q;
    vis[s]=true;
    pre[s].u=s;
    q.push(s);
    while (!q.empty()) {
        int u=q.front();
        q.pop();
        for (int i=head[u];i+1;i=edge[i].nxt) {
            int v=edge[i].v;
            if (!vis[v]&&edge[i].w) {
                pre[v].u=u;
                pre[v].ecnt=i;
                vis[v]=true;
                if (v==t) {
                    return true;
                }
                q.push(v);
            }
        }
    }
    return false;
}

int EK()
{
    int ans=0;
    while (bfs()) {
        int mi=INF;
        for (int i=t;i!=s;i=pre[i].u) {
            mi=min(mi,edge[pre[i].ecnt].w);
        }
        for (int i=t;i!=s;i=pre[i].u) {
            edge[pre[i].ecnt].w-=mi;
            edge[pre[i].ecnt^1].w+=mi;
        }
        ans+=mi;
    }
    return ans;
}

int main()
{
    init();
    scanf("%d%d%d%d",&n,&m,&s,&t);
    while (m--) {
        int u,v,w;
        scanf("%d%d%d",&u,&v,&w);
        addEdge(u,v,w);
        addEdge(v,u,0);
    }
    printf("%d
",EK());
    return 0;
}

原文地址:https://www.cnblogs.com/xyqxyq/p/12328895.html