最小费用最大流模板

博客提供了最小费用最大流模板。最小费用最大流是信息技术领域算法相关内容,该模板可用于解决特定的网络流问题,在相关算法应用场景中具有重要作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<bits/stdc++.h>
using namespace std;
#define REP(i, s, e) for(register int i = s; i <= e ;i++)
const int maxn = 5000 + 5, maxm = 50000 + 5, inf((((1 << 30) - 1) << 1) + 1);
int bg[maxn], ne[maxm << 1], to[maxm << 1], w[maxm << 1], cost[maxm << 1], e = 1;

inline void add(int x, int y, int z, int c)
{
	e++;
	to[e] = y;
	ne[e] = bg[x];
	bg[x] = e;
	w[e] = z;
	cost[e] = c;
}

int n, m, S, T;

int max_flow, min_cost;

queue <int> q;
bool vis[maxn];
int dis[maxn], pre[maxn], Max[maxn];
inline bool spfa()
{
	memset(vis, 0, sizeof(vis));
	REP(i, 1, n) dis[i] = inf;
	dis[S] = 0;
	while (!q.empty()) q.pop();
	q.push(S);
	Max[S] = inf;
	
	while (!q.empty())
	{
		register int x = q.front();
		q.pop();
		vis[x] = 0;
		for (register int i = bg[x]; i ; i = ne[i])
			if (w[i] > 0 && dis[to[i]] > dis[x] + cost[i])
			{
				dis[to[i]] = dis[x] + cost[i];
				pre[to[i]] = i;
				Max[to[i]] = min(Max[x], w[i]);
				if (!vis[to[i]])
				{
					vis[to[i]] = 1;
					q.push(to[i]);
				}
			}
	}
	return dis[T] != inf;
}

inline void update()
{
	int x = T;
	while (x != S)
	{
		w[pre[x]] -= Max[T];
		w[pre[x] ^ 1] += Max[T];
		x = to[pre[x] ^ 1];
	}
	max_flow += Max[T];
	min_cost += Max[T] * dis[T];
}

int main(){
	cin >> n >> m >> S >> T;
	while (m--)
	{
		int x, y, z, c;
		scanf("%d%d%d%d", &x, &y, &z, &c);
		add(x, y, z, c);
		add(y, x, 0, -c);
	}
	while (spfa()) update();
	cout << max_flow << ' ' << min_cost;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值