POJ - 1273-Drainage Ditches (网络流--最大流模板题)

题目:戳我呀

题解:网络流最大流模板题,想了解网络流模板可以去这里学习一下

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<set>
#include<queue>
#include<vector>
#include<stack>
#define INF 0x3f3f3f3f
#define N 205
#define M 205
#define LL long long
using namespace std;
int n,m,c;
int head[N],cur[N],deep[N];
struct ljh
{
	int to,next;
	LL w;
}e[2*M];
inline void add(int x,int y,LL z)
{
	e[c].next=head[x];
	e[c].w=z;
	e[c].to=y;
	head[x]=c++;
}
bool bfs(int s,int t)
{
	memset(deep,0,sizeof(deep));
	deep[s]=1;
	queue<int>q;
	q.push(s);
	while(!q.empty())
	{
		int now=q.front();
		q.pop();
		for(int i=head[now];i!=-1;i=e[i].next)
		{
			 int nex=e[i].to;
			 if(deep[nex]==0&&e[i].w>0)
			 {
			 	deep[nex]=deep[now]+1;
			 	q.push(nex);
			 }
		}
	}
	return deep[t];
}
LL dfs(int x,int t,LL maxflow)
{
	if(x==t)return maxflow;
	LL ans=0;
	for(int i=head[x];i!=-1;i=e[i].next)
	{
		int nex=e[i].to;
		if(deep[nex]!=deep[x]+1||e[i].w<=0||ans>=maxflow)continue;
		cur[x]=i;
		LL k=dfs(nex,t,min(e[i].w,maxflow-ans));
		e[i].w-=k;
		e[i^1].w+=k;
		ans+=k;
	}
	if(ans==0)deep[x]=-2;//炸点优化
	return ans;
}
LL Dinic(int s,int t)
{
	LL ans=0;
	while(bfs(s,t))
	{
		memcpy(cur,head,sizeof(head));
		ans+=dfs(s,t,INF);
	}
	return ans;
}
int main()
{
	while(~scanf("%d%d",&m,&n))
	{
		c=0;
		memset(head,-1,sizeof(head));
		for(int i=1;i<=m;i++)
		{
			int x,y;
			LL z;
			scanf("%d%d%lld",&x,&y,&z);
			add(x,y,z);
			add(y,x,0);
		}
		printf("%lld\n",Dinic(1,n));
	}
}
/*
5 4
1 2 40
1 4 20
2 4 20
2 3 30
3 4 10
6 5
1 2 4
2 4 3
4 5 5
3 5 4
2 3 2
1 3 6
*/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值