2174. 费用流(费用流,模板题)

描述了一种在有向图中使用SPFA算法求解最大流和最小费用问题的方法,特别指出在最大费用最大流和最小费用最大流中的应用区别。
摘要由CSDN通过智能技术生成

活动 - AcWing

给定一个包含 n 个点 m 条边的有向图,并给定每条边的容量和费用,边的容量非负。

图中可能存在重边和自环,保证费用不会存在负环。

求从 S 到 T 的最大流,以及在流量最大时的最小费用。

输入格式

第一行包含四个整数 n,m,S,T。

接下来 m 行,每行三个整数 u,v,c,w,表示从点 u 到点 v 存在一条有向边,容量为 c,费用为 w。

点的编号从 1 到 n。

输出格式

输出点 S 到点 T 的最大流和流量最大时的最小费用。

如果从点 S 无法到达点 T 则输出 0

数据范围

2≤n≤5000,
1≤m≤50000,
0≤c≤100,
−100≤w≤100
S≠T

输入样例:
5 5 1 5
1 4 10 5
4 5 5 10
4 2 12 5
2 5 10 15
1 5 10 10
输出样例:
20 300

解析: 

对于 n 个节点,m 条边的流网络,可以在 O(nm^2) 的时间复杂度内求出该流网络的 最小费用最大流(最大费用最大流)。

算法步骤:

用 while 循环不断判断残量网络中是否存在增广路径。

对于循环中:

1.找到增广路径
2.更新残量网络
3.累加最大流量
4.循环结束,得出最大流。

注意: EK 算法原本是用于求最大流的,但是经过严格的证明之后,只需要将 EK 算法中找增广路径的 bfs 算法替换成 spfa 算法即可。如果要求最小费用最大流,就用 spfa 算法找最短增广路;如果要求最大费用最大流,就用 spfa 算法找最长增广路。(注意:由于是使用spfa求最短路,所以费用不能有负环)

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>
#include<sstream>
#include<deque>
#include<unordered_map>
#include<unordered_set>
#include<bitset>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
const int N = 5e3 + 10, M = (5e4) * 2 + 10, INF = 0x3f3f3f3f;
int n, m, S, T;
int h[N], e[M], f[M], w[M], ne[M], idx;
int q[N], dist[N], incf[N],pre[N];
bool st[N];

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

bool spfa() {
	int hh = 0, tt = 1;
	memset(dist, 0x3f, sizeof dist);
	memset(incf, 0, sizeof incf);
	q[0] = S, dist[S] = 0, incf[S] = INF;
	while (hh != tt) {
		int t = q[hh++];
		if (hh == N)hh = 0;
		st[t] = 0;
		for (int i = h[t]; i != -1; i = ne[i]) {
			int j = e[i];
			if (f[i] && dist[j] > dist[t] + w[i]) {
				dist[j] = dist[t] + w[i];
				incf[j] = min(incf[t], f[i]);
				pre[j] = i;
				if (!st[j]) {
					st[j] = 1;
					q[tt++] = j;
					if (tt == N)tt = 0;
				}
			}
		}
	}
	return incf[T] > 0;
}

void EK(int& flow, int& cost) {
	flow = cost = 0;
	while (spfa()) {
		int t = incf[T];
		flow += t, cost += t * dist[T];
		for (int i = T; i != S; i = e[pre[i] ^ 1]) {
			f[pre[i]] -= t;
			f[pre[i] ^ 1] += t;
		}
	}
}

int main() {
	cin >> n >> m >> S >> T;
	memset(h, -1, sizeof h);
	for (int i = 1,a,b,c,d; i <= m; i++) {
		scanf("%d%d%d%d", &a, &b, &c, &d);
		add(a, b, c, d);
	}
	int flow, cost;
	EK(flow, cost);
	cout << flow << " " << cost << endl;
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值