最大流dinic 模板

5 篇文章 0 订阅
2 篇文章 0 订阅

rt

#include <bits/stdc++.h>
using namespace std;

#define _rep(i, a, b) for (int i = (a); i <= (b); ++i)
#define _rev(i, a, b) for (int i = (a); i >= (b); --i)
#define _for(i, a, b) for (int i = (a); i < (b); ++i)
#define _rof(i, a, b) for (int i = (a); i > (b); --i)
#define oo 0x3f3f3f3f
#define ll long long
#define db double
#define eps 1e-8
#define bin(x) cout << bitset<10>(x) << endl;
#define what_is(x) cerr << #x << " is " << x << "s" << endl;
#define met(a, b) memset(a, b, sizeof(a))
#define all(x) x.begin(), x.end()
#define pii pair<int, int>
const int maxn = 2e5 + 10, max_deepth = 1e5;
int m, n, s, t;
struct node
{
	int nxt, to, cost;
} way[maxn];
int head[maxn], cnt = 1, deep[maxn], flow_max;
void addedge(int from, int to, int cost)
{
	way[++cnt].to = to;
	way[cnt].cost = cost;
	way[cnt].nxt = head[from];
	head[from] = cnt;
}
inline int nxt()
{
	int ret;
	scanf("%d", &ret);
	return ret;
}
bool bfs(int s, int t)//残量网络上构造分层图
{
	queue<int> q;
	q.push(s);
	met(deep, 0);
	deep[s] = 1;
	while (!q.empty())
	{
		int cur = q.front();
		q.pop();
		for (int i = head[cur]; i; i = way[i].nxt)
		{
			int to = way[i].to, cost = way[i].cost;
			if (cost && !deep[to])//没来过
			{
				deep[to] = deep[cur] + 1;
				q.push(to);
				if(to == t)return 1;
			}
		}
	}
	return 0;
}
int dfs(int cur, int flow){
	if(cur == t)return flow;
	int rest = flow, k;
	for(int i = head[cur];i && rest;i = way[i].nxt){
		int to = way[i].to, cost = way[i].cost;
		if(deep[to] == deep[cur] + 1 && cost){
			k = dfs(to, min(rest, cost));
			if(!k)deep[to] = 0;
			way[i].cost -= k;
			way[i^1].cost += k;
			rest -= k;
		}
	}
	return flow - rest;
}
void Dinic(int s, int t)
{
	while (bfs(s, t))
		flow_max += dfs(s, oo);
	cout << flow_max << endl;
}
int main()
{
	n = nxt(), m = nxt(), s = nxt(), t = nxt();
	_rep(i, 1, m)
	{
		int from = nxt(), to = nxt(), cost = nxt();
		addedge(from, to, cost), addedge(to, from, 0);
	}
	Dinic(s, t);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值