-
Notifications
You must be signed in to change notification settings - Fork 438
/
Edmonds-Karp.cpp
136 lines (114 loc) · 1.91 KB
/
Edmonds-Karp.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include <cstdio>
#include <cstring>
#define VERTEX_COUNT 210
#define EDGE_COUNT 20000
using namespace std;
struct vertex
{
int first_edge;
int pree, prev;
}V[VERTEX_COUNT];
bool vis[VERTEX_COUNT];
struct edge
{
int endp, next;
int flow;
}E[EDGE_COUNT];
int ec = 2;
int ivc, iec;
int maxflow = 0;
int Q[VERTEX_COUNT];
int hp = 0, tp = 0;
inline int min(int x, int y)
{
return x < y ? x : y;
}
void add_edge(int u, int v, int f)
{
E[ec].next = V[u].first_edge;
V[u].first_edge = ec;
E[ec].endp = v;
E[ec].flow = f;
ec++;
}
inline void enqueue(int x)
{
Q[tp++] = x;
}
inline int dequeue()
{
return Q[hp++];
}
inline bool isempty()
{
return hp == tp;
}
inline void empty()
{
hp = tp = 0;
}
void Edmonds_Karp(int s, int t)
{
bool has_ap;
do
{
has_ap = false;
memset(vis, false, sizeof(vis));
empty();
enqueue(s);
while (!isempty())
{
int u = dequeue();
for (int cur = V[u].first_edge; cur != 0; cur = E[cur].next)
{
if (E[cur].flow > 0)
{
if (E[cur].endp == t)
{
has_ap = true;
int p = u, pathmin = E[cur].flow;
while (p != 1)
{
pathmin = min(pathmin, E[V[p].pree].flow);
p = V[p].prev;
}
p = u;
E[cur].flow -= pathmin;
E[cur ^ 1].flow += pathmin;
while (p != 1)
{
E[V[p].pree].flow -= pathmin;
E[V[p].pree ^ 1].flow += pathmin;
p = V[p].prev;
}
maxflow += pathmin;
goto END;
}
else if (vis[E[cur].endp] == false)
{
V[E[cur].endp].pree = cur;
V[E[cur].endp].prev = u;
vis[E[cur].endp] = true;
enqueue(E[cur].endp);
}
}
}
}
END:;
} while (has_ap == true);
}
int main()
{
// e.g. CodeVS - 1993.
scanf("%d%d", &iec, &ivc);
for (int i = 0; i < iec; i++)
{
int u, v, f;
scanf("%d%d%d", &u, &v, &f);
add_edge(u, v, f);
add_edge(v, u, 0);
}
Edmonds_Karp(1, ivc);
printf("%d", maxflow);
return 0;
}