Dinic 网络流

写个博客贴板子……

inline void add_edge(int x,int y,int z){
	e[++tot].x=y,e[tot].cap=z;
	e[tot].next=h[x],h[x]=tot;
	e[++tot].x=x,e[tot].cap=0;
	e[tot].next=h[y],h[y]=tot;
}

bool bfs(){
	queue<int> q;
	memset(deth,-1,sizeof(deth));
	deth[S]=0,q.push(S),cur[S]=h[S];
	while(!q.empty()){
		int x=q.front();q.pop();
		for(int i=h[x];i;i=e[i].next){
			if(!e[i].cap||~deth[e[i].x])continue;
			deth[e[i].x]=deth[x]+1;
			cur[e[i].x]=h[e[i].x];
			q.push(e[i].x);
			if(e[i].x==T)return true;
		}
	}
	return false;
}

int dfs(int x,int flow){
	if(x==T)return flow;
	for(int &i=cur[x];i;i=e[i].next)
		if(e[i].cap&&deth[e[i].x]==deth[x]+1){
			int sum=dfs(e[i].x,min(flow,e[i].cap));
			if(sum>0){
				e[i].cap-=sum,e[i^1].cap+=sum;
				return sum;
			}
		}
	return 0;
}

int dinic(){
	int ans=0,k;
	while(bfs())
	while(k=dfs(S,2e9))ans+=k;
	return ans;
}
posted @ 2018-10-03 09:27  ezoiLZH  阅读(217)  评论(0编辑  收藏  举报