【网络流】【模板】最小费用最大流

L i n k Link

l u o g u luogu P 3381 P3381

D e s c r i p t i o n Description

如题,给出一个网络图,以及其源点和汇点,每条边已知其最大流量和单位流量费用,求出其网络最大流和在最大流情况下的最小费用。

I n p u t Input

第一行包含四个正整数N、M、S、T,分别表示点的个数、有向边的个数、源点序号、汇点序号。

接下来M行每行包含四个正整数ui、vi、wi、fi,表示第i条有向边从ui出发,到达vi,边权为wi(即该边最大流量为wi),单位流量的费用为fi。

O u t p u t Output

一行,包含两个整数,依次为最大流量和在最大流量情况下的最小费用。

S a m p l e Sample I n p u t Input

4 5 4 3
4 2 30 2
4 3 20 3
2 3 20 1
2 1 30 9
1 3 40 5

S a m p l e Sample O u t p u t Output

50 280

H i n t Hint

时空限制:1000ms,128M

(BYX:最后两个点改成了1200ms)

数据规模:

对于30%的数据:N<=10,M<=10

对于70%的数据:N<=1000,M<=1000

对于100%的数据:N<=5000,M<=50000

样例说明:
在这里插入图片描述
如图,最优方案如下:

第一条流为4–>3,流量为20,费用为3*20=60。

第二条流为4–>2–>3,流量为20,费用为(2+1)*20=60。

第三条流为4–>2–>1–>3,流量为10,费用为(2+9+5)*10=160。

故最大流量为50,在此状况下最小费用为60+60+160=280。

故输出50 280。

T r a i n Train o f of T h o u g h t Thought

因为是模板,也没什么好说的
就是一个SPFA求最小费用的增广路,然后增广就好了
不懂网络流的可以先看看我之前的blog:网络流最大流模板

C o d e Code

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>

using namespace std;
const int inf = 1e9;

int flow_, ans_flow, ans_val, n, m, s, t, tt;
int h[100005], dis[100005], c[100005], prev[100005];

struct node
{
	int from, to, flow, val, num, next;
}g[100005];

void add(int x, int y, int w, int z)
{
	g[++tt] = (node) {x, y, w, z, tt + 1, h[x]}; h[x] = tt;
	g[++tt] = (node) {y, x, 0, -z, tt - 1, h[y]}; h[y] = tt;
}

bool spfa()
{
	memset(c, 0, sizeof(c));
	queue<int>Q;
	for (int i = 1; i <= n; ++i) dis[i] = inf;
	dis[s] = 0;
	c[s] = 1;
	Q.push(s);
	while (Q.size())
	{
		int x = Q.front();
		Q.pop();
		for (int i = h[x]; i; i = g[i].next)
		{
			if (g[i].flow && dis[g[i].to] > dis[x] + g[i].val)
			{
				dis[g[i].to] = dis[x] + g[i].val;
				prev[g[i].to] = i;//记录到这个点的边的编号
				if (!c[g[i].to]) {
					Q.push(g[i].to);
					c[g[i].to] = 1;
				}//加入队列
			} 
		}
		c[x] = 0;
	}
	if (dis[t] == inf) return 0;
	 else return 1;//判断是否还有增广路
}

void mcf()
{
	int x;
	flow_ = inf; x = t;
	while (prev[x])
	{
		flow_ = min(flow_, g[prev[x]].flow);
		x = g[prev[x]].from;
	}
	ans_flow += flow_; ans_val += flow_ * dis[t];
	x = t;
	while (prev[x])
	{
		g[prev[x]].flow -= flow_;
		g[g[prev[x]].num].flow += flow_;
		x = g[prev[x]].from;
	}
}//增广

int main()
{
	scanf("%d%d%d%d", &n, &m, &s, &t);
	for (int i = 1; i <= m; ++i)
	{
		int u, v, w, z;
		scanf("%d%d%d%d", &u, &v, &w, &z);
		add(u, v, w, z);
	}
	while (spfa()) mcf();
	printf("%d %d", ans_flow, ans_val);
} 

猜你喜欢

转载自blog.csdn.net/LTH060226/article/details/104000325