模板 最大流

dinic算法加上当前弧优化计算最大流

#include<bits/stdc++.h>
#define LL long long
#define PII pair<int,int>
#define PLI pair<LL,int>;v
#define lson o<<1,l,mid
#define rson o<<1|1,mid+1,r
#define lowbit(x) (x&(-x))
using namespace std;

const int maxn=210,maxm=5010;
const int inf=1e9+10;
int n,m,s,t;
int head[maxn],nxt[2*maxm],to[2*maxm],weight[2*maxm],cnt,depth[maxn],cur[maxn];

void init(){
    memset(head,-1,sizeof(head));
    cnt=0;
}

void add(int u,int v,LL w){
    to[cnt]=v;
    weight[cnt]=w;
    nxt[cnt]=head[u];
    head[u]=cnt++;
}

void add_edge(int u,int v,LL w){
    add(u,v,w);
    add(v,u,0);
}

int dfs(int u,int flow){
    if(u==t) return flow;
    for(int& i=cur[u];~i;i=nxt[i]){
        int v=to[i];
        if(depth[v]==depth[u]+1 && weight[i]!=0){
            int di=dfs(v,min(flow,weight[i]));
            if(di>0){
                weight[i]-=di;
                weight[i^1]+=di;
                return di;
            }
        }
    }
    return 0;
}

bool bfs(){
    queue<int> q;
    memset(depth,0,sizeof(depth));
    depth[s]=1;
    q.push(s);
    while(!q.empty()){
        int u=q.front();
        q.pop();
        for(int i=head[u];~i;i=nxt[i]){
            int v=to[i];
            if(depth[v]==0 && weight[i]>0){
                depth[v]=depth[u]+1;
                q.push(v);
            }
        }
    }
    if(depth[t]>0) return 1;
    return 0;
}

int dinic(){
    int ans=0;
    while(bfs()){
        for(int i=1;i<=n;i++){
            cur[i]=head[i];
        }
        while(int d=dfs(s,inf)){
            ans+=d;
        }
    }
    return ans;
}

int main(){
    scanf("%d %d %d %d",&n,&m,&s,&t);
    init();
    for(int i=0;i<m;i++){
        int u,v,w;
        scanf("%d %d %d",&u,&v,&w);
        add_edge(u,v,w);
    }
    int ans=dinic();
    printf("%d\n",ans);
}
posted @ 2020-06-22 16:10  fxq1304  阅读(102)  评论(0编辑  收藏  举报