Dinic优化板子

Code

struct Net_flow{
    LL S,T;
    struct node{
        LL to,nxt,flow;
    }dis[Maxn];
    LL num,nod;
    LL head[maxn],lev[maxn],cur[maxn];
    inline void Init(){
    	num=-1; memset(head,-1,4*(nod+1));
    }
    inline void Add(LL u,LL v,LL flow){
        dis[++num]=(node){v,head[u],flow}; head[u]=num;
        dis[++num]=(node){u,head[v],0}; head[v]=num;
    }
    std::queue<LL> que;
    inline bool Bfs(){
        memset(lev,0,4*(nod+1)); lev[S]=1; que.push(S);
        	for(LL i=1;i<=nod;++i) cur[i]=head[i];
        while(que.size()){
            LL u(que.front()); que.pop();
            for(LL i=head[u];i!=-1;i=dis[i].nxt){
                if(!dis[i].flow) continue;
                LL v(dis[i].to); if(lev[v]) continue;
                lev[v]=lev[u]+1; que.push(v);
            }
        }
        return lev[T]!=0;
    }
    LL Dfs(LL u,LL flow){
        if(u==T) return flow;
        LL tmp(flow);
        for(LL& i=cur[u];i!=-1;i=dis[i].nxt){
            LL v(dis[i].to);
        	if(lev[v]!=lev[u]+1 || !dis[i].flow) continue;
            LL t(Dfs(v,std::min(tmp,dis[i].flow)));
            if(t){
                tmp-=t; dis[i].flow-=t; dis[i^1].flow+=t;
                if(!tmp) return flow;
			}else lev[v]=-1;
        }return flow-tmp;
    }
    inline LL Dinic(){
        LL ret(0);
        while(Bfs()){
        	ret+=Dfs(S,inf);
		}
        return ret;
    }
}G;
posted @ 2019-05-27 16:54  y2823774827y  阅读(176)  评论(0编辑  收藏  举报