zoukankan      html  css  js  c++  java
  • 最大流dinic板子

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

    #include <bits/stdc++.h>
    using namespace std;
    const int MAXN=1e5+5;
    const int INF=0x7fffffff;
    typedef long long ll;
    int n,m,s,t;
    int head[MAXN<<1],tot;
    struct node
    {
        int to,nxt,flow;
    }e[MAXN<<1];
    void add(int x,int y,int z)
    {
        e[tot].to=y;e[tot].nxt=head[x];e[tot].flow=z;head[x]=tot++;
    }
    void add_edge(int x,int y,int z)
    {
        add(x,y,z);add(y,x,0);
    }
    ll deep[MAXN],tail,be,q[MAXN];
    bool bfs()
    {
        memset(deep,0,sizeof(deep));
        deep[s]=1;
        ll be=0,tail=1;
        q[1]=s;
        while(be!=tail)
        {
            ll u=q[++be];
            for(int i=head[u];~i;i=e[i].nxt)
            {
                if(!deep[e[i].to]&&e[i].flow)
                {
                    deep[e[i].to]=deep[u]+1;
                    q[++tail]=e[i].to;
                }
            }
        }
        return deep[t];
    }
    int dfs(int now,int fa1)
    {
        if(now==t)return fa1;
        int fa=0;
        for(int i=head[now];~i&&fa1;i=e[i].nxt)
        {
            if(deep[e[i].to]==deep[now]+1&&e[i].flow)
            {
                int d=dfs(e[i].to,min(fa1,e[i].flow));
                if(d>0)
                {
                    e[i].flow-=d;
                    e[i^1].flow+=d;
                    fa1-=d;
                    fa+=d;
                }
            }
        }
        if(!fa)deep[now]=-1;
        return fa;
    }
    ll dinic()
    {
        ll res=0;
        while(bfs())
        {
            res+=dfs(s,INF);
        }
        return res;
    }
    int main()
    {
        memset(head,-1,sizeof(head));
        scanf("%d%d%d%d",&n,&m,&s,&t);
        for(int i=1;i<=m;i++)
        {
            int x,y,z;scanf("%d%d%d",&x,&y,&z);
            add_edge(x,y,z);
        }
        int ans=dinic();
        printf("%d
    ",ans);
        return 0;
    }
  • 相关阅读:
    测试计划设计
    测试方案
    使用gulp构建自动化工作流
    ESLint--定制你的代码规则
    Node.js学习笔记(一):快速开始
    React-Native性能优化点
    ES6笔记(一):ES6所改良的javascript“缺陷”
    windows下React-native 环境搭建
    使用ssh连接gitHub
    javascript中的prototype和constructor
  • 原文地址:https://www.cnblogs.com/ljxdtc666/p/12356945.html
Copyright © 2011-2022 走看看