演算法導論—最大流(Edmonds-Karp演算法)
阿新 • • 發佈:2019-01-05
華電北風吹
天津大學認知計算與應用重點實驗室
2016-07-20
有向圖的最大流演算法程式碼模板。利用廣度優先搜尋尋找殘量網路增廣路。
參考程式碼:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define maxn 10
#define INT_MIN 0x80000000
struct Edge
{
int from, to, capacity, flow;
Edge(int u, int v, int c, int f) :from(u), to(v), capacity(c), flow(f){}
};
struct EdmondsKarp
{
int n, m;
vector<Edge> edges;
vector<int> G[maxn];
int a[maxn];
int p[maxn];
void Init(int n)
{
for (int i = 0; i < n; i++)
{
G[i].clear();
}
edges.clear();
}
void AddEdge(int from, int to, int capacity)
{
edges.push_back(Edge(from, to, capacity, 0));
edges.push_back(Edge(to, from, 0, 0));
m = edges.size();
G[from].push_back(m - 2);
G[to].push_back(m - 1);
}
int MaxFlowComputation(int s, int t)
{
int flow = 0;
while (true )
{
memset(a, 0, sizeof(a));
queue<int> Q;
Q.push(s);
a[s] = INT_MIN;
while (Q.empty()==false)
{
int x = Q.front();
Q.pop();
for (int i = 0; i < G[x].size(); i++)
{
Edge & e = edges[G[x][i]];
if ((a[e.to] == 0) && (e.capacity>e.flow))
{
p[e.to] = G[x][i];
a[e.to] = min(a[x], e.capacity - e.flow);
Q.push(e.to);
}
}
if (a[t] > 0)
{
break;
}
}
if (a[t] == 0)
{
break;
}
for (int u = t; u != s; u = edges[p[u]].from)
{
edges[p[u]].flow += a[t];
edges[p[u] ^ 1].flow -= a[t];
}
flow += a[t];
}
return flow;
}
};