C++ 基于Dijkstra最短路搜索的Ford Fulkson最大流算法

本文详细阐述了最大流算法的实现过程,并通过实例展示了如何使用该算法解决实际问题。

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

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<ctime>
#include<cstring>

using namespace std;

const int MAXN = 120;
const int INF = INT_MAX;

int G[MAXN][MAXN], N;

int dist[MAXN], Pre[MAXN];
bool visited[MAXN];

int times = 0;

bool Dijkstra(int src, int dest) {
	for (int i = 0; i < N; ++i) {
		dist[i] = INF;
	}
	for (int i = 0; i < N; ++i) {
		Pre[i] = -1;
	}

	for (int i = 0; i < N; ++i) {
		visited[i] = false;
	}

	dist[src] = 0;

	for (int i = 0; i < N - 1; ++i) {
		//extract min
		int nd = -1;
		for (int i = 0; i < N; ++i) {
			if (!visited[i] && (nd == -1 || dist[i] < dist[nd]))
				nd = i;
		}
		if (dist[nd] == INF) 
			break;
		visited[nd] = true;

		//relax.
		for (int i = 0; i < N; ++i) {
			if (!visited[i] && G[nd][i] > 0 && dist[i] > dist[nd] + G[nd][i]) {
				dist[i] = dist[nd] + G[nd][i];
				Pre[i] = nd;
			}
		}
	}
	
	/*
	cout << (++times) << ": ";
	int e = dest;
	cout << dest << " ";
	while (Pre[e] != -1) {
		cout << Pre[e] << " ";
		e = Pre[e];
	}
	cout << endl;
	*/

	if (dist[dest] != INF)
		return true;
	else
		return false;
}

int Mx_flow(int src, int dest) {
	int ans = 0;

	while (Dijkstra(src, dest)) {
		int min_f = INF;

		//find min_f.
		int e = dest;
		while (Pre[e] != -1) {
			if (G[Pre[e]][e] < min_f)
				min_f = G[Pre[e]][e];
			e = Pre[e];
		}

		//cout << "minf: " << min_f << endl;

		//undate residual network
		e = dest;
		while (Pre[e] != -1) {
			G[Pre[e]][e] -= min_f;
			G[e][Pre[e]] += min_f;
			e = Pre[e];
		}

		//accumulate mx_flow.
		ans += min_f;
	}

	return ans;
}

int main(void) {
	memset(G, 0, sizeof(G));

	cin >> N;

	int m;
	cin >> m;
	for (int i = 0; i < m; ++i) {
		int s, t, c;
		cin >> s >> t >> c;
		G[s][t] = c;
	}

	int mx_f = 0;
	int src, dest;
	cin >> src >> dest;

	clock_t  t = clock();
	mx_f = Mx_flow(src, dest);
	cout << "Time: " << (clock() - t) << "(ms)" << endl;
	cout << "Max_flow: " << mx_f << endl;

	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值