日后有时间在详细解说 先将代码附上
C++实现代码如下:
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
typedef struct edge {
int to, cap, rev;
}Edge;
#define MAX_V 5
#define INF 99999999
vector<Edge> G[MAX_V];
bool used[MAX_V];
void add_edge(int from, int to, int cap) {
G[from].push_back(Edge{ to, cap, (int)G[to].size() });
G[to].push_back(Edge{ from,0,(int)G[from].size() - 1 });
}
int min(int a, int b) {
return a < b ? a : b;
}
int dfs(int v, int t, int f) {
if (v == t)
return f;
used[v] = true;
for (int i = 0; i < G[v].size(); ++i) {
Edge &e = G[v][i];
if (!used[e.to] && e.cap > 0) {
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
cout << "e.rev = " << e.rev << endl;
cout << d << endl;
return d;
}
}
}
return 0;
}
int max_flow(int s, int t) {
int flow = 0;
for (;;) {
memset(used, 0, sizeof(used));
int f = dfs(s, t, INF);
if (f == 0) {
return flow;
}
flow += f;
cout << f << " " << flow << endl;
//flow += f;
}
return -1;
}
int main()
{
cout << "请输入源和目的地:";
int r, s;
cin >> r >> s;
cout << "接下来请输入每条边的信息(from,to,cap)当from=-1的时候终止输入:" << endl;
int from, to, cap;
cin >> from >> to >> cap;
while (from != -1){
add_edge(from, to, cap);
cin >> from >> to >> cap;
}
cout << "源到目的地的最大流为 " <<max_flow(r, s) << endl;
return 0;
}
测试 数据:
1 5
1 2 10
1 3 2
2 3 6
2 4 6
3 5 5
4 3 3
4 5 8
-1 0 0
答案是11