首页 > 代码库 > [洛谷P3376]【模板】网络最大流

[洛谷P3376]【模板】网络最大流

题目大意:略。

解题思路:最大流木板题,以下是Dinic算法的代码。

C++ Code:

 

#include<stdio.h>#include<cctype>#include<vector>#include<algorithm>#include<cstring>#include<queue>using namespace std;#define INF 0x3f3f3f3fchar buf[40000020];int bufpos,n,m,s,t,level[10002],iter[10002];struct edges{	int to,cap,rev;	edges(int t,int c,int r):to(t),cap(c),rev(r){}};vector<edges>G[10002];queue<int>q;inline void init(){    buf[fread(buf,1,40000000,stdin)]=‘\0‘;    bufpos=0;}inline int readint(){	int p=0;    for(;!isdigit(buf[bufpos]);bufpos++);    for(;isdigit(buf[bufpos]);bufpos++)    p=p*10+buf[bufpos]-‘0‘;    return p;}inline void addedge(int from,int to,int cap){	G[from].push_back(edges(to,cap,G[to].size()));	G[to].push_back(edges(from,0,G[from].size()-1));}void bfs(int s){	memset(level,-1,sizeof(level));	level[s]=0;	q.push(s);	while(!q.empty()){		int u=q.front();		q.pop();		for(int i=0;i<G[u].size();++i){			edges& e=G[u][i];			if(level[e.to]<0&&e.cap>0){				level[e.to]=level[u]+1;				q.push(e.to);			}		}	}}int dfs(int u,int t,int f){	if(u==t)return f;	for(int& i=iter[u];i<G[u].size();++i){		edges& e=G[u][i];		if(e.cap>0&&level[e.to]>level[u]){			int d=dfs(e.to,t,min(f,e.cap));			if(d){				e.cap-=d;				G[e.to][e.rev].cap+=d;				return d;			}		}	}	return 0;}int max_flow(int s,int t){	int flow=0;	while(1){		bfs(s);		if(level[t]<0)return flow;		memset(iter,0,sizeof(iter));		int f;		while(f=dfs(s,t,INF))flow+=f;	}}int main(){	#ifdef DEBUG	freopen("input.txt","r",stdin);	freopen("output.txt","w",stdout);	#endif	init();	n=readint(),m=readint(),s=readint(),t=readint();	for(int i=1;i<=m;++i){		int u=readint(),v=readint(),cap=readint();		addedge(u,v,cap);	}	printf("%d\n",max_flow(s,t));	return 0;}

 

[洛谷P3376]【模板】网络最大流