题解 P3376 【【模板】网络最大流】(EK)

luogu


#include<bits/stdc++.h>
using namespace std;
int inf=2147483647;
int n,m,s,t;
int ans;
int bj[1000010];
int tot=1,head[1000010];
int ip1,ip2,ip3;
struct Edge
{
    int to,d,next;
}edge[1000010];
struct Pre
{
    int X,E;
}pre[1000010];
void addedge(int st,int en,int D)
{
    edge[++tot].to=en;
    edge[tot].d=D;
    edge[tot].next=head[st];
    head[st]=tot;
}
int bfs()
{
    queue<int>q;
    memset(bj,0,sizeof(bj));
    memset(pre,-1,sizeof(pre));
    bj[s]=1;
    q.push(s);
    while(!q.empty())
    {
        int now=q.front();
        q.pop();
        for(int i=head[now];i;i=edge[i].next)
        {
            int T=edge[i].to;
            if(edge[i].d&&!bj[T])
            {
                pre[T].X=now;
                pre[T].E=i;
                if(T==t)
                {
                    return 1;
                }
                bj[T]=1;
                q.push(T);
            }
        }
    }
    return 0;
}
void EK()
{
    ans=0;
    while(bfs())
    {
        int MIN=inf;
        for(int i=t;i!=s;i=pre[i].X)
        {
            MIN=min(MIN,edge[pre[i].E].d);
        }
        for(int i=t;i!=s;i=pre[i].X)
        {
            edge[pre[i].E].d-=MIN;
            edge[pre[i].E^1].d+=MIN;
        }
        ans+=MIN;
    }
}
int main()
{
    scanf("%d%d%d%d",&n,&m,&s,&t);
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&ip1,&ip2,&ip3);
        addedge(ip1,ip2,ip3);
        addedge(ip2,ip1,0);
    }
    EK();
    cout<<ans;
}
posted @ 2019-04-05 15:31  G_A_TS  阅读(474)  评论(0编辑  收藏  举报