网络流

 

#include<bits/stdc++.h>
using namespace std;
#define ll long long
int n,m,s,t;
struct edge
{
    int to,nxxt,len;
}e[1001001<<1];
int head[1001001],cnt=-1;
inline void addedge(int u,int v,int w)
{
    cnt++;
    e[cnt].to=v;
    e[cnt].len=w;
    e[cnt].nxxt=head[u];
    head[u]=cnt;
}
inline void superadd(int u,int v,int w)
{
    addedge(u,v,w);
    addedge(v,u,0);
}
queue<int>q;
int deep[1001001],vis[1001001];
inline bool bfs()
{
    while(!q.empty())q.pop();
    memset(deep,0,sizeof deep);
    deep[s]=1;
    q.push(s);
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        for(int i=head[u];~i;i=e[i].nxxt)
        {
            if(e[i].len==0)continue;
            int to=e[i].to;
            if(!deep[to])
            {
                deep[to]=deep[u]+1;
                q.push(to);
            }
        }
    }
    return deep[t]!=0;
}
inline int dfs(int u,int tar)
{
    if(u==t)return tar;
    int now=0;
    for(int i=head[u];~i;i=e[i].nxxt)
    {
        if(!e[i].len)continue;
        int to=e[i].to;
        if(deep[to]<=deep[u])continue;
        int num=dfs(to,min(tar,e[i].len));
        now+=num;
        tar-=num;
        e[i].len-=num;
        e[i^1].len+=num;
        if(!tar)return now;
    }
    return now;
}
int main()
{
    memset(head,-1,sizeof head);
    scanf("%d%d%d%d",&n,&m,&s,&t);
    for(int i=1;i<=m;i++)
    {
        int u,v,w;
        scanf("%d%d%d",&u,&v,&w);
        superadd(u,v,w);
    }
    int ans=0;
    while(bfs())ans+=dfs(s,2.1e9);
    printf("%d",ans);
}
网络流

网络流

posted @ 2019-04-23 18:35  david_alwal  阅读(90)  评论(0编辑  收藏  举报