【網絡流】【模板】最小費用最大流

LinkLink

luoguluogu P3381P3381

DescriptionDescription

如題,給出一個網絡圖,以及其源點和匯點,每條邊已知其最大流量和單位流量費用,求出其網絡最大流和在最大流情況下的最小費用。

InputInput

第一行包含四個正整數N、M、S、T,分別表示點的個數、有向邊的個數、源點序號、匯點序號。

接下來M行每行包含四個正整數ui、vi、wi、fi,表示第i條有向邊從ui出發,到達vi,邊權爲wi(即該邊最大流量爲wi),單位流量的費用爲fi。

OutputOutput

一行,包含兩個整數,依次爲最大流量和在最大流量情況下的最小費用。

SampleSample InputInput

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

SampleSample OutputOutput

50 280

HintHint

時空限制: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。

TrainTrain ofof ThoughtThought

因爲是模板,也沒什麼好說的
就是一個SPFA求最小費用的增廣路,然後增廣就好了
不懂網絡流的可以先看看我之前的blog:網絡流最大流模板

CodeCode

#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);
} 
發佈了224 篇原創文章 · 獲贊 35 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章