-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflownetwork.py
executable file
·105 lines (88 loc) · 3.22 KB
/
flownetwork.py
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
class Edge:
def __init__(self, u, v, w, r=False):
self.source = u
self.sink = v
self.capacity = w
self.reverse = r
def __repr__(self):
return "%s->%s:%s" % (self.source, self.sink, self.capacity)
class FlowNetwork:
def __init__(self):
self.adj = {}
self.flow = {}
def add_vertex(self, vertex):
self.adj[vertex] = []
def get_edges(self, v):
return self.adj[v]
def add_edge(self, u, v, w=0):
if u == v:
raise ValueError("u == v")
edge = Edge(u,v,w)
redge = Edge(v,u,0, True)
edge.redge = redge
redge.redge = edge
self.adj[u].append(edge)
self.adj[v].append(redge)
self.flow[edge] = 0
self.flow[redge] = 0
def find_path(self, source, sink, path):
if source == sink:
return path
for edge in self.get_edges(source):
residual = edge.capacity - self.flow[edge]
if residual > 0 and edge not in path and edge.redge not in path:
result = self.find_path( edge.sink, sink, path + [edge])
if result != None:
return result
def maxLength_path(self, source, sink):
if source == sink:
return []
children = []
for edge in self.adj[source]:
if not edge.reverse:
children.append((edge.sink, edge))
# print(source, ":", children)
maxPath = []
firstEdge = None
maxPathLength = -1
for value in children:
child, sourceChildEdge = value
path = self.maxLength_path(child, sink)
# print(source, ":", path)
if path is None:
continue
# if len(path) == 0:
# return [sourceChildEdge]
if len(path) > maxPathLength:
maxPath = path
firstEdge = sourceChildEdge
maxPathLength = len(path)
if maxPathLength == -1:
return None
# firstSink = maxPath[0].source
# firstEdge = None
# for edge in self.adj[source]:
# if (not edge.reverse) and edge.source == source and edge.sink == firstSink:
# firstEdge = edge
return [firstEdge] + maxPath
def max_flow(self, source, sink):
path = self.find_path(source, sink, [])
while path != None:
residuals = [edge.capacity - self.flow[edge] for edge in path]
flow = min(residuals)
for edge in path:
self.flow[edge] += flow
self.flow[edge.redge] -= flow
path = self.find_path(source, sink, [])
return sum(self.flow[edge] for edge in self.get_edges(source))
def max_flow_gen(self, source, sink):
path = self.find_path(source, sink, [])
while path != None:
residuals = [edge.capacity - self.flow[edge] for edge in path]
flow = min(residuals)
for edge in path:
self.flow[edge] += flow
self.flow[edge.redge] -= flow
yield (self, path)
path = self.find_path(source, sink, [])
yield sum(self.flow[edge] for edge in self.get_edges(source))