最大流(relable-front)算法
预流推进算法2(relable-front)算法,时间复杂度O(v^3)
1 // The relable-front algorithm code due to CLRS chapter 26
2 #include<iostream>
3 #include<list>
4 using namespace std;
5 const int N = 100;
6 int n; // vertex number
7 int e[N]; // residual flow of the vertex
8 int h[N]; // height of the vertex
9 int c[N][N]; // capacity of the edge
10 int f[N][N]; // flow of the edge
11 list<int> ev; // excess flow vertex
12 list<int> edge[N]; // edge link list
13
14 inline void Push(int u, int v) // push flow from edge (u, v)
15 {
16 int df = min(e[u], c[u][v] - f[u][v]);
17 f[u][v] += df;
18 f[v][u] = -f[u][v];
19 e[u] -= df;
20 e[v] += df;
21 }
22
23 void Relable(int u) // re-lable heght of vertex u
24 {
25 h[u] = n * 2 - 1;
26 for(list<int>::iterator iter = edge[u].begin(); iter != edge[u].end(); iter++)
27 {
28 if(c[u][*iter] > f[u][*iter] && h[*iter] < h[u])
29 h[u] = h[*iter];
30 }
31 h[u]++;
32 }
33
34 void Discharge(int u) // discharge the residual flow of vertex u
35 {
36 list<int>::iterator iter = edge[u].begin();
37 while(e[u] > 0)
38 {
39 if(iter == edge[u].end())
40 {
41 Relable(u);
42 iter = edge[u].begin();
43 }
44 if(h[u] == h[*iter] + 1 && c[u][*iter] > f[u][*iter])
45 Push(u, *iter);
46 ++iter;
47 }
48 }
49
50 void Init_PreFlow()
51 {
52 ev.clear();
53 h[0] = n;
54 e[0] = 0;
55 memset(f, 0 , sizeof(f));
56 for (int u = 1; u < n; u++)
57 {
58 f[0][u] = c[0][u];
59 f[u][0] = -f[0][u];
60 e[u] = c[0][u];
61 if(u != n - 1)
62 ev.push_back(u);
63 }
64
65 // construct link list
66 for(int u = 0; u < n; u++)
67 for(int v = u + 1; v < n; v++)
68 {
69 if(c[u][v] > 0 || c[v][u] > 0)
70 {
71 edge[u].push_back(v);
72 edge[v].push_back(u);
73 }
74 }
75 }
76
77 int Relable_To_Front()
78 {
79 Init_PreFlow();
80 list<int>::iterator iter = ev.begin();
81 int old_height, frontV;
82 while(iter != ev.end())
83 {
84 old_height = h[*iter];
85 Discharge(*iter);
86 if(h[*iter] > old_height)
87 {
88 frontV = *iter;
89 ev.erase(iter);
90 ev.push_front(frontV);
91 iter = ev.begin();
92 }
93 iter++;
94 }
95 return e[n-1];
96 }
97
98 int main()
99 {
100 int m, u, v, w;
101 while(scanf("%d%d", &m, &n) != EOF)
102 {
103 memset(c, 0, sizeof(c));
104 for(int i = 0; i < m; i++)
105 {
106 scanf("%d%d%d", &u, &v, &w);
107 c[u][v] = w;
108 }
109 printf("Max Flow is %d\n", Relable_To_Front());
110 }
111 return 0;
112 }