hdu1532 Drainage Ditches (Dinic)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1532


题解:模版题。


#include <stdio.h>
#include <string.h>
#define INF 0x7fffffff
#define MAXN 202

struct node
{
	int to,cap,next;
}edge[MAXN<<1];

int head[MAXN],level[MAXN],queue[MAXN];
int tot,src,dest;

int Scan()                      
{                      
	char ch;                      
	int ret=0;                      
	while((ch=getchar())<'0'||ch>'9');                      
	while(ch>='0'&&ch<='9')                      
	{                      
		ret=ret*10+(ch-'0');                      
		ch=getchar();                      
	}                      
	return ret;                      
} 

int getMin(int x,int y)
{
	return x<y?x:y;
}

void addEdge(int m)
{
	int u,v,val;
	tot=0;
	memset(head,-1,sizeof(head));
	while(m--)
	{
		u=Scan();
		v=Scan();
		val=Scan();
		edge[tot].to=v;
		edge[tot].cap=val;
		edge[tot].next=head[u];
		head[u]=tot++;

		edge[tot].to=u;
		edge[tot].cap=0;
		edge[tot].next=head[v];
		head[v]=tot++;
	}
}

int BFS()
{
	int front=0,rear=1,v,i;
	memset(level,0,sizeof(level));
	queue[0]=src;
	level[src]=1;
	while(front<rear)
	{
		v=queue[front++];
		if(v==dest)
			return 1;
		for(i=head[v];i!=-1;i=edge[i].next)
		{
			if(!level[edge[i].to]&&edge[i].cap>0)
			{
				level[edge[i].to]=level[v]+1;
				queue[rear++]=edge[i].to;
			}
		}
	}
	return 0;
}

int DFS(int cur,int maxf)
{
	int ret=0,i,temp,v;
	if(cur==dest)
		return maxf;
	for(i=head[cur];i!=-1;i=edge[i].next)
	{
		v=edge[i].to;
		if(edge[i].cap>0&&level[v]==level[cur]+1)
		{
			temp=DFS(v,getMin(maxf-ret,edge[i].cap));
			edge[i].cap-=temp;
			edge[i^1].cap+=temp;
			ret+=temp;
			if(maxf==ret)
				return ret;
		}
	}
	return ret;
}

int main()
{
	int n,m,maxflow,temp;
	while(scanf("%d %d",&m,&n)!=EOF)
	{
		addEdge(m);
		src=1,dest=n;
		maxflow=0;
		while(BFS())
		{
			maxflow+=DFS(src,INF);
		}
		printf("%d\n",maxflow);
	}
	return 0;
}


你可能感兴趣的:(hdu1532 Drainage Ditches (Dinic))