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

题目链接:

https://www.luogu.com.cn/problem/P3376

算法:1:FF算法模板

注意:对一条单向边要存其反向边,因此存边的数组要开2倍

#include <bits/stdc++.h>

using namespace std;
const int maxn=1e4+1,maxm=2e5+1;
int n,m,s,t,tot=1,head[maxn],vis[maxn];

struct edge
{
    int to,next,w;
}e[maxm];

void addedge(int x,int y,int w)
{
    e[++tot].to=y;
    e[tot].w=w;
    e[tot].next=head[x];
    head[x]=tot;
}

int dfs(int x,int flow)//在没有走到汇点前,我们不知道流量是多少,所以flow是动态更新的
{
    if(x==t)return flow;//走到汇点返回本次增广的流量
    vis[x]=1;
    for(int i=head[x];i;i=e[i].next)
    {
        int y=e[i].to,w=e[i].w;
        if(w&&!vis[y])//不要重复经过,如果到的点没有残余可以用的流量,那么走过去也没用
        {
            int t=dfs(y,min(flow,w));
            if(t>0)//顺着流过去,要受一路上最小容量的限制
            {
                e[i].w-=t;//此边残余容量减小并建立反向边
                e[i^1].w+=t;
                return t;
            }
        }
    }
    return 0;//无法到汇点
}

int main()
{
    ios::sync_with_stdio(0);
    scanf("%d %d %d %d",&n,&m,&s,&t);
    for(int i=1;i<=m;i++)
    {
        int x,y,w;scanf("%d %d %d",&x,&y,&w);
        addedge(x,y,w);addedge(y,x,0);
        /*反向边开始容量为0,表示不允许平白无故走反向边
        只有正向边流量过来以后,才提供返还流量的机会*/
    }
    int res=0,ans=0;
    while(memset(vis,0,sizeof(vis))&&(res=dfs(s,1e9/*假设flow很大*/))>0)ans+=res;
    printf("%d\n",ans);
    return 0;
}
发布了119 篇原创文章 · 获赞 39 · 访问量 7595

猜你喜欢

转载自blog.csdn.net/aiwo1376301646/article/details/104253217