POJ1273

最大流的入门。。。。用于刷ac率的水题

#include
#include
#include
#include
const int MAXN=1e5+5;
const int INF=0x7fffffff;
struct Edge
{
	long long f;
	int to;
	int nxt;
}edge[MAXN<<1];
int num=1;
int head[MAXN];
int dist[MAXN];
bool vis[MAXN];
void add(int from,int to,long long f)
{
	edge[++num].nxt=head[from];
	edge[num].to=to;
	edge[num].f=f;
	head[from]=num;
	edge[++num].nxt=head[to];
	edge[num].to=from;
	edge[num].f=0;
	head[to]=num;
}
int src;
int sink;
bool bfs()
{
	std::queueq;
	std::memset(dist,0,sizeof(dist));
	std::memset(vis,0,sizeof(vis));
	q.push(src);
	dist[0]=0;
	vis[src]=1;
	while(!q.empty())
	{
		int u=q.front();
		q.pop();
		for(int i=head[u];i;i=edge[i].nxt)
		{
			int v=edge[i].to;
			if(!vis[v]&&edge[i].f)
			{
				dist[v]=dist[u]+1;
				q.push(v);
				vis[v]=1;
			}
		}
	}
	return vis[sink];
}
long long maxflow(int x,long long delta)
{
	if(x==sink)
	{
		return delta;
	}
	long long res=0;
	for(int i=head[x];i;i=edge[i].nxt)
	{
		int v=edge[i].to;
		if(dist[v]==dist[x]+1&&edge[i].f)
		{
			long long dd=maxflow(v,std::min(edge[i].f,delta));
			res+=dd;
			delta-=dd;
			edge[i].f-=dd;
			edge[i^1].f+=dd;
		}
	}
	return res;
}
int main()
{
	int m,n;
	while(std::scanf("%d%d",&m,&n)==2)
	{
		num=1;
		std::memset(edge,0,sizeof(edge));
		std::memset(head,0,sizeof(head));
			src=1;
	sink=n;
	for(int i=1;i<=m;i++)
	{
		int u,v;
		long long f;
		std::scanf("%d%d%I64d",&u,&v,&f);
		add(u,v,f);
	}
	long long ans=0;
	while(bfs())
	{
		ans+=maxflow(src,INF);
	}
	std::printf("%I64d\n",ans);
	}
	return 0;
}

你可能感兴趣的:(NOIP,NOI)