很久之前就想攻克一下网络流的问题了,一直拖着,一是觉得这部分的内容好像非常高级,二是还有很多其他算法也需要学习,三是觉得先补补相关算法会好点
不过其实这虽然是图论比较高级的内容,但是基础打好了,那么还是不会太难的,而且它的相关算法并不多,熟悉图论之后就可以学习了,就算法不会二分图也可以学习。
这里使用Ford-Fulkerson算法,其实现的方法叫做:Edmonds-Karp
Algorithm
其实两者前者是基本算法思想,后者是具体实现方法。
两个图十分清楚:
图1:原图,求这个图的最大网络流
图2:19+4 = 23 为其最大网络流
图片出处: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; 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。
Geeks Ford-Fulkerson Algorithm for Maximum Flow Problem 最大网络流问题,布布扣,bubuko.com
时间: 2024-12-05 22:16:25