Dinic 萌新求助

P3376 【模板】网络最大流

WTR2007 @ 2021-11-08 21:59:19

#include<bits/stdc++.h>
#define long long int;
using namespace std;
int p=1,n,m,s,t,head[205],cur[205],dep[205],flag[205][205];
struct node{
    int to,nxt,val;
}e[10005];
inline int read(){
    int w=0;
    char ch=getchar();
    while(ch<'0'||ch>'9') ch=getchar();
    while(ch>='0' && ch<='9'){
        w=(w<<1)+(w<<3)+(ch-48);
        ch=getchar();
    }
    return w;
}
void add(int from,int t,int v){
    e[++p].to=t;
    e[p].val=v;
    e[p].nxt=head[from];
    head[from]=p;
}
bool bfs(){
    queue<int> q;
    for(int i=1;i<=n;i++){
        cur[i]=head[i];
        dep[i]=0x3f3f3f;
    }
    q.push(s);dep[s]=0;
    while(!q.empty()){
        int x=q.front();q.pop();
        for(int i=head[x];i;i=e[i].nxt){
            int u=e[i].to;
            if(dep[u]>dep[x]+1 && e[i].val){
                dep[u]=dep[x]+1;
                q.push(u);
                if(u==t) return 1;
            }
        }
    }
    if(dep[t]>=0x3f3f3f) return 0;
    else return 1;
}
int dfs(int x,int low){
    if(x==t) return low;    
    int used=0;
    for(int i=cur[x];i;i=e[i].nxt){
        cur[x]=i;
        int u=e[i].to;
        if(!e[i].val || dep[u]!=dep[x]+1) continue;
        int mi=dfs(u,min(low-used,e[i].val));
        if(mi>0){
            used+=mi;
            e[i].val-=mi;
            e[i^1].val+=mi;
            if(used==low) break;
        }
    }
    return used;
}
int Dinic(){
    int ans=0;
    while(bfs()){
        ans+=dfs(s,0x3f3f3f);
    }
    return ans;
}
int main(){
    n=read();m=read();s=read();t=read();
    for(int i=1;i<=m;i++){
        int a,b,c;
        a=read();b=read();c=read();
        if(!flag[a][b]){
            add(a,b,c);
            flag[a][b]=p;
            add(b,a,0);
        }
        else e[flag[a][b]].val+=c;
    }
    printf("%d\n",Dinic());
    return 0;
}

|