-
Notifications
You must be signed in to change notification settings - Fork 538
Expand file tree
/
Copy pathmaxflow.py
More file actions
209 lines (179 loc) · 6.42 KB
/
maxflow.py
File metadata and controls
209 lines (179 loc) · 6.42 KB
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
"""
Courtesy of Steven Halim, Felix Halim, Suhendry Effendy
CP4 Free Source Code Project (cpp/gnu++17, java/java11, py/python3, and ml/ocaml).
https://github.com/stevenhalim/cpbook-code/blob/master/ch8/maxflow.py
"""
from numbers import Number
from copy import deepcopy
INF = float('inf')
class MaxFlow:
def __init__(self, V: int):
"""
Creates a new instance of the MaxFlow class. The general way you'll
want to use this library is to create a new instance of the class,
add edges, then call the `edmonds_karp` or `dinic` methods.
While the library does support floats, be aware that it is not advised
to use due to the potential for floating point errors, meaning small
amounts of flow may be sent many times.
Arguments:
V: The number of vertices in the graph.
Example:
>>> mf = MaxFlow(3)
>>> mf.add_edge(0, 1, 3)
>>> mf.add_edge(0, 2, 3)
>>> mf.add_edge(1, 2, 3)
>>> mf.dinic(0, 2) # or mf.edmonds_karp(0, 2)
6
"""
self.V = V
self.EL = []
self.AL = [list() for _ in range(self.V)]
self.d = []
self.last = []
self.p = []
self.has_been_run = False
def BFS(self, s: int, t: int) -> bool:
self.d = [-1] * self.V
self.d[s] = 0
self.p = [[-1, -1] for _ in range(self.V)]
q = [s]
while len(q) != 0:
u = q[0]
q.pop(0)
if u == t:
break
for idx in self.AL[u]:
v, cap, flow = self.EL[idx]
if cap - flow > 0 and self.d[v] == -1:
self.d[v] = self.d[u]+1
q.append(v)
self.p[v] = [u, idx]
return self.d[t] != -1
def send_one_flow(self, s: int, t: int, f: Number = INF) -> Number:
if s == t:
return f
u, idx = self.p[t]
_, cap, flow = self.EL[idx]
pushed = self.send_one_flow(s, u, min(f, cap-flow))
flow += pushed
self.EL[idx][2] = flow
self.EL[idx ^ 1][2] -= pushed
return pushed
def DFS(self, u: int, t: int, f: Number = INF) -> Number:
if u == t or f == 0:
return f
for i in range(self.last[u], len(self.AL[u])):
self.last[u] = i
v, cap, flow = self.EL[self.AL[u][i]]
if self.d[v] != self.d[u]+1:
continue
pushed = self.DFS(v, t, min(f, cap - flow))
if pushed != 0:
flow += pushed
self.EL[self.AL[u][i]][2] = flow
self.EL[self.AL[u][i] ^ 1][2] -= pushed
return pushed
return 0
def add_edge(self, u: int, v: int, capacity: Number,
directed: bool = True) -> None:
"""
Adds an edge from `u` to `v` with capacity `w`. By default, the edge is
directed, i.e. `u`->`v`. You can set `directed = False` to add it
as an undirected edge `u`<->`v`.
Arguments:
`u`: The first vertex.
`v`: The second vertex.
`capacity`: The capacity of the edge.
`directed`: Whether the edge is directed. True by default.
Example:
>>> mf = MaxFlow(3)
>>> mf.add_edge(0, 1, 3)
>>> mf.add_edge(2, 1, 3)
"""
if u == v:
return
self.EL.append([v, capacity, 0])
self.AL[u].append(len(self.EL)-1)
self.EL.append([u, 0 if directed else capacity, 0])
self.AL[v].append(len(self.EL)-1)
def assert_has_not_already_been_run(self):
if self.has_been_run:
msg = ('Rerunning a max flow algorithm on the same graph will '
+ 'result in incorrect behaviour. Please use .copy() '
+ 'before you run any max flow algorithm if you need to '
+ 'run multiple iterations')
raise Exception(msg)
self.has_been_run = True
def edmonds_karp(self, s: int, t: int) -> Number:
"""
Returns the max flow obtained by running Edmons-Karp algorithm.
Modifies the graph in place.
Arguments:
`s`: The source vertex.
`t`: The sink vertex.
Returns:
The max flow.
"""
self.assert_has_not_already_been_run()
mf = 0
while self.BFS(s, t):
f = self.send_one_flow(s, t)
if f == 0:
break
mf += f
return mf
def dinic(self, s: int, t: int) -> Number:
"""
Returns the max flow obtained by running Dinic's algorithm.
Modifies the graph in place.
Arguments:
`s`: The source vertex.
`t`: The sink vertex.
Returns:
The max flow.
"""
self.assert_has_not_already_been_run()
mf = 0
while self.BFS(s, t):
self.last = [0] * self.V
f = self.DFS(s, t)
while f != 0:
mf += f
f = self.DFS(s, t)
return mf
def copy(self) -> 'MaxFlow':
"""
Returns a deep copy of the current instance. This is convenient for
problems where you need to run MaxFlow multiple times on slightly
different graphs, since the instance is destroyed after each max flow
run.
Example:
>>> mf = MaxFlow(4)
>>> mf.add_edge(0, 1, 3)
>>> mf.add_edge(1, 2, 3)
>>> for c in range(1, 4):
>>> mf_copy = mf.copy()
>>> mf_copy.add_edge(2, 3, c)
>>> res = mf_copy.dinic(0, 3) # Will not modify mf
"""
return deepcopy(self)
def __repr__(self) -> str:
el = self.EL[:10] + ['...'] if len(self.EL) > 10 else self.EL
al = self.AL[:10] + ['...'] if len(self.AL) > 10 else self.AL
el = ', '.join(map(str, el))
al = ', '.join(map(str, al))
return f'MaxFlow(V={self.V}, EL=[{el}], AL=[{al}])'
def main():
fp = open('maxflow_in.txt', 'r')
V, s, t = map(int, fp.readline().strip().split())
mf = MaxFlow(V)
for u in range(V):
tkn = list(map(int, fp.readline().strip().split()))
k = tkn[0]
for i in range(k):
v, w = tkn[2*i+1], tkn[2*i+2]
mf.add_edge(u, v, w)
# print(mf.edmonds_karp(s, t))
print(mf.dinic(s, t))
if __name__ == '__main__':
main()