Geeks Ford-Fulkerson Algorithm for Maximum Flow Problem 最大网络流问题

很久之前就想攻克一下网络流的问题了,一直拖着,一是觉得这部分的内容好像非常高级,二是还有很多其他算法也需要学习,三是觉得先补补相关算法会好点

不过其实这虽然是图论比较高级的内容,但是基础打好了,那么还是不会太难的,而且它的相关算法并不多,熟悉图论之后就可以学习了,就算法不会二分图也可以学习。

这里使用Ford-Fulkerson算法,其实现的方法叫做:Edmonds-Karp Algorithm

两个图十分清楚:

图1:原图,求这个图的最大网络流

ford_fulkerson1

图2:19+4 = 23 为其最大网络流

ford_fulkerson2


图片出处:http://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/


#include <stdio.h>
#include <iostream>
#include <string.h>
#include <queue>
using namespace std;

const int V = 6;

bool bfs(int rGraph[V][V], int s, int t, int parent[])
{
	bool vis[V] = {0};

	queue<int> qu;
	qu.push(s);
	vis[s] = true;

	while (!qu.empty())
	{
		int u = qu.front();
		qu.pop();

		for (int v = 0; v < V; v++)
		{
			if (!vis[v] && rGraph[u][v] > 0)
			{
				qu.push(v);
				parent[v] = u;
				vis[v] = true;
			}
		}
	}
	return vis[t];
}

// Returns tne maximum flow from s to t in the given graph
int fordFulkerson(int graph[V][V], int s, int t)
{
	int rGraph[V][V];

	for (int u = 0; u < V; u++)
		for (int v = 0; v < V; v++)
			rGraph[u][v] = graph[u][v];

	int parent[V];
	int maxFlow = 0;

	while (bfs(rGraph, s, t, parent))
	{
		int pathFlow = INT_MAX;
		for (int v = t; v != s; v = parent[v])
			pathFlow = min(pathFlow, rGraph[parent[v]][v]);

		for (int v = t; v != s; v = parent[v])
		{
			rGraph[parent[v]][v] -= pathFlow;
			rGraph[v][parent[v]] += pathFlow;
		}
		maxFlow += pathFlow;
	}
	return maxFlow;
}

int main()
{
	// Let us create a graph shown in the above example
	int graph[V][V] = { 
		{0, 16, 13, 0, 0, 0},
		{0, 0, 10, 12, 0, 0},
		{0, 4, 0, 0, 14, 0},
		{0, 0, 9, 0, 0, 20},
		{0, 0, 0, 7, 0, 4},
		{0, 0, 0, 0, 0, 0}
	};

	cout << "The maximum possible flow is " << fordFulkerson(graph, 0, 5)<<'\n';
	return 0;
}



结果是23。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值