最小费用最大流(Bellman-Ford)C++实现

#include 
#include 
#include 
#include 
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 edges;
vector 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 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;
	}
}

 

你可能感兴趣的:(C++,算法)