acwing Dinic求最大流

https://www.acwing.com/problem/content/2174/

 

Dinic算法的时间复杂度是O(N^2M),N为点数,M为边数

模板题:

#include <bits/stdc++.h>
using namespace std;
//Filename: Dinic.cpp
//
//Author: dezhonger - csdisassembly@gmail.com

//Create: 2020-11-14 18:48:11

//时间复杂度: O(N^2*M)

const int N = 10010, M = 200001, INF = 1e8;

int n, m, S, T;
int h[N], e[M], f[M], ne[M], idx;
//q是队列,d是分层路,cur是当前弧优化
int q[N], d[N], cur[N];

void add(int a, int b, int c) {
	e[idx] = b, f[idx] = c, ne[idx] = h[a], h[a] = idx++;
	e[idx] = a, f[idx] = 0, ne[idx] = h[b], h[b] = idx++;
}

bool bfs() {
	int hh = 0, tt = 0;
	memset(d, -1, sizeof d);
	q[0] = S, d[S] = 0, cur[S] = h[S];
	while (hh <= tt) {
		int t = q[hh++];
		for (int i = h[t]; ~i; i = ne[i]) {
			int ver = e[i];
			//如果这个点没有搜过并且流量大于0
			if (d[ver] == -1 && f[i]) {
				d[ver] = d[t] + 1;
				cur[ver] = h[ver];
				if (ver == T) return true;
				q[++tt] = ver;
			}
		}
	}
	return false;
}

int find(int u, int limit) {
	if (u == T) return limit;
	int flow = 0;
	//从当前没有满的路径开始搜
	for (int i = cur[u]; ~i && flow < limit; i = ne[i]) {
		cur[u] = i; //当前弧优化
		int ver = e[i];
		if (d[ver] == d[u] + 1 && f[i]) {
			int t = find(ver, min(f[i], limit - flow));
			//从这个点出发是搜不到路径的,就删除这个点
			if (!t) d[ver] = -1;
			f[i] -= t, f[i ^ 1] += t, flow += t;
		}
	}
	return flow;
}

int dinic() {
	int r = 0, flow;
	while (bfs()) {
		while (flow = find(S, INF)) r += flow;
	}
	return r;
}
int main() {
	scanf("%d%d%d%d", &n, &m, &S, &T);
	memset(h, -1, sizeof h);
	while (m--) {
		int a, b, c;
		scanf("%d%d%d", &a, &b, &c);
		add(a, b, c);
	}
	printf("%d\n", dinic());
	return 0;
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值