• Dinic


    #include<iostream>
    #include<cstring>
    #include<cstdio>
    #include<stack>
    #define N 1000005
    #define inf 0x3f3f3f3f
    using namespace std;
    
    struct Edge{
        int to,nxt,cap;
    };
    
    int que[N];
    int h,qt;
    
    struct Dinic{
        Edge e[N];
        bool vis[N];
        int tot,s,t,n;
        int d[N],cur[N],head[N];
        Dinic(){tot=1;}
        void add(int u,int v,int f){
            e[++tot].to=v;
            e[tot].cap=f;
            e[tot].nxt=head[u];
            head[u]=tot;
            e[++tot].to=u;
            e[tot].cap=0;
            e[tot].nxt=head[v];
            head[v]=tot;
        }
        bool bfs(){
            memset(vis,false,sizeof(vis));
            for(int i=0;i<=n;++i)cur[i]=head[i];
            que[qt=1]=s,h=0;int top,to;d[s]=0;vis[s]=1;
            while(h<qt){
                top=que[++h];
                for(int i=head[top];i;i=e[i].nxt)
                    if(!vis[e[i].to]&&e[i].cap){
                        to=e[i].to;que[++qt]=to;
                        vis[to]=true;d[to]=d[top]+1;
                        if(to==t)return true;
                    }
            }
            return vis[t];
        }
        int dfs(int x,int fl){
            if(x==t)return fl;
            int flow=0,f,to;
            for(int &i=cur[x];i;i=e[i].nxt){
                to=e[i].to;
                if(d[to]==d[x]+1&&e[i].cap)
                if(f=dfs(to,min(fl,e[i].cap))){
                    e[i].cap-=f;fl-=f;
                    e[i^1].cap+=f;flow+=f;
                    if(fl<=0)break;
                }
            }
            if(fl)d[x]=-1;
            return flow;
        }
        int maxflow(int s,int t){
            this->s=s;this->t=t;
            int ans=0;
            while(bfs())ans+=dfs(s,inf);
            return ans;
        }
    };
    int main(){
        int n,m,s,t,a,b,c;
        scanf("%d%d%d%d",&n,&m,&s,&t);
        Dinic f;f.n=n;
        for(int i=1;i<=m;++i){
            scanf("%d%d%d",&a,&b,&c);
            f.add(a,b,c);
        }
        cout<<f.maxflow(s,t);
        return 0;
    }
    
    
    
  • 相关阅读:
    Jzoj4765 Crisis
    Jzoj4764 Brothers
    Jzoj4764 Brothers
    Jzoj4756 幻象
    Jzoj4756 幻象
    Jzoj4755 快速荷叶叶变换
    Jzoj4755 快速荷叶叶变换
    力扣算法题—059螺旋矩阵
    力扣算法题—058最后一个单词长度
    力扣算法题—057插入区间
  • 原文地址:https://www.cnblogs.com/qdscwyy/p/8092977.html
Copyright © 2020-2023  润新知