最小費用最大流(Bellman-Ford)C++實現

#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
#define N 1010
typedef struct edge
{
	int from;
	int to;
	int cap;
	int flow;
	int cost;
}Edge;
int a[N], p[N], d[N], inq[N];
vector<Edge> edges;
vector<int> G[N];
int n, m, s, t, T;
int fflow = 0, total_cost = 0;
bool Bellman_Ford(int, int);

int main()
{
	int a, b, c, co;
	cin >> T;
	while (T--)
	{
		cin >> n >> m >> s >> t;
		for (int i = 1; i <= m; i++)
		{
			cin >> a >> b >> c >> co;
			Edge e;
			e.from = a; e.to = b; e.cap = c; e.cost = co; e.flow = 0;
			edges.push_back(e);
			e.from = b; e.to = a; e.cap = 0; e.cost = -co; e.flow = 0;
			edges.push_back(e);
			int num = edges.size();
			G[a].push_back(num - 2);
			G[b].push_back(num - 1);
		}
		while (Bellman_Ford(s, t));
		cout << fflow << endl;
		cout << total_cost << endl;
	}

	system("pause");
	return 0;
}

bool Bellman_Ford(int s, int t)
{
	memset(a, 0, sizeof(a));
	memset(p, 0, sizeof(p));
	memset(inq, 0, sizeof(inq));
	for (int i = 1; i <= n; i++)
	{
		d[i] = 1000000;
	}
	a[s] = 10000;
	d[s] = 0;
	queue<int> Q;
	Q.push(s);
	p[s] = 0;
	inq[s] = 1;
	while (!Q.empty())
	{
		int x = Q.front(); Q.pop(); inq[x] = 0;
		for (int i = 0; i < G[x].size(); i++)
		{
			Edge& e = edges[G[x][i]];
			if (e.cap > e.flow && d[e.to] > d[x] + e.cost)//若該點能夠被鬆弛,下面更新a,p,d,並判斷該點能否入隊。
			{
				d[e.to] = d[x] + e.cost;
				p[e.to] = G[x][i];
				a[e.to] = min(a[x], e.cap - e.flow);
				if (inq[e.to] == 0)
				{
					Q.push(e.to); inq[e.to] = 1;
				}
			}
		}
	}
	//Bellman_Ford在當前殘量圖中鬆弛完畢後,下面更新其所涉及邊的流量變化。
	//首先查看d[t]是否發生了變化,若不變,則說明已無增廣路
	if (d[t] == 1000000)
	{
		return false;
	}
	else//若d[t]的值得到更新,則考慮更新殘量圖
	{
		fflow += a[t];
		total_cost += d[t] * a[t];
		for (int i = t; i != s; i = edges[p[i]].from)
		{
			edges[p[i]].flow += a[t];
			edges[p[i]^1].flow -= a[t];
		}
		return true;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章