网络流(dinic)模板

· · 个人记录

#include<bits/stdc++.h>
using namespace std;
using type=int;
const type inf=(1<<30);
#define debug cerr<<x<<" "<<y<<" "<<flow<<endl;
const int MaxN=1e4+5,MaxM=1e6+5;
struct edge{
    int next,to;
    type flow;
}e[MaxM<<1];
int head[MaxN],cnt=1;
inline void ADD(int x,int y,type flow){
    e[++cnt]={head[x],y,flow};
    head[x]=cnt;
}
inline void add(int x,int y,type flow){
    ADD(x,y,flow);
    ADD(y,x,0);
}
int dep[MaxN],cur[MaxN];
inline bool bfs(int s,int t){
    queue<int>q;
    q.push(s);
    memset(dep,0,sizeof(dep));
    cur[s]=head[s];
    dep[s]=1;
    while(!q.empty()){
        int x=q.front();
        q.pop();
        for(int i=head[x];i;i=e[i].next){
            int y=e[i].to;
            if(dep[y]||!e[i].flow){
                continue;
            }
            dep[y]=dep[x]+1;
            cur[y]=head[y];
            q.push(y);
            if(y==t){
                return 1;
            }
        }
    }
    return 0;
}
inline type dfs(int x,type flow,int t){
    if(x==t||!flow){
        return flow;
    }
    type limit,res=0;
    for(int i=cur[x];i&&flow;i=e[i].next){
        cur[x]=i;
        int y=e[i].to;
        if(dep[y]==dep[x]+1&&e[i].flow){
            limit=dfs(y,min(flow,e[i].flow),t);
            if(!limit){
                dep[y]=0;
            }else{
                e[i].flow-=limit;
                e[i^1].flow+=limit;
                res+=limit;
                flow-=limit;
            }
        }
    }
    return res;
}
inline type dinic(int s,int t){
    type res=0;
    while(bfs(s,t)){
        res+=dfs(s,inf,t);
    }
    return res;
}
inline void init(){
    memset(head,0,sizeof(head));
    cnt=1;
}
int s,t,n,m;
inline void build(){
    cin>>n>>m;
    cout<<dinic(s,t)<<'\n';
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    t=MaxN-1;
    build();
    return 0;
}