最大流模板(洛谷3376)

Posted by yjjr's blog on February 6, 2018
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#define rep(i,a,b) for(register int i=a;i<=b;i++)
#define dep(i,a,b) for(register int i=a;i>=b;i--)
#define reg(x) for(int i=last[x];i;i=e[i].next)
#define ll long long
#define mem(x,num) memset(x,num,sizeof(x))
#define inf 1844387848
using namespace std;
inline ll read()
{
    ll f=1,x=0;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
const int maxn=1e5+6,maxq=1e6+6;
struct edge{ll to,from,v,t,next;}e[maxn<<1];
ll n,m,k,cnt=1,ans,s,t,last[maxn],que[maxq],h[maxq];
 
bool bfs()
{
    ll head=0,tail=0,now;
    mem(h,-1);que[0]=s,h[s]=0;
    while(head<=tail){
        now=que[head++];
        reg(now)
            if(e[i].v&&h[e[i].to]==-1){h[e[i].to]=h[now]+1;que[++tail]=e[i].to;}
    }
    if(h[t]==-1)return 0;else return 1;
}
int dfs(int x,int f)
{
    if(x==t)return f;
    ll w,used=0;
    reg(x)
        if(e[i].v&&h[e[i].to]==h[x]+1){
            w=f-used;w=dfs(e[i].to,min(w,e[i].v));
            e[i].v-=w;e[i^1].v+=w;
			used+=w;if(used==f)return f;
        }
    if(!used)h[x]=-1;
    return used;
}
void dinic(){while(bfs())ans+=dfs(s,inf);}

int main()
{ 
    n=read(),m=read(),s=read(),t=read();
    rep(i,1,m){
        ll u=read(),v=read(),w=read();
        e[++cnt]=(edge){v,u,w,w,last[u]};last[u]=cnt;
        e[++cnt]=(edge){u,v,0,-w,last[v]};last[v]=cnt;
    }
    dinic();
    cout<<ans<<endl;
    return 0;
}
本文可以转载,但必须附上原文链接,否则你会终生找不到妹子!!!欢迎关注我的CSDN: ahyjjr