网络流dinic算法模板python
作者:
endinggy
,
2022-02-10 15:14:44
,
所有人可见
,
阅读 292
dist, cur = [0] * n, [0] * n
def bfs():
for i in range(n): dist[i] = cur[i] = 0
q = deque([S]); dist[S] = 1
while q:
u = q.popleft()
for v in e[u]:
if not dist[v] and cap[u][v]:
dist[v] = dist[u] + 1
q.append(v)
if v == T: return 1
return 0
def dfs(u, f):
if u == T: return f
max_flow = 0
i = cur[u]
while i < len(e[u]) and max_flow < f:
v, cur[u], i = e[u][i], i, i + 1
if cap[u][v] and dist[v] == dist[u] + 1:
ff = dfs(v, min(f - max_flow, cap[u][v]))
if ff == 0: dist[v] = 0
cap[u][v] -= ff
cap[v][u] += ff
max_flow += ff
return max_flow
ans = 0
while bfs(): ans += dfs(S, 10 ** 9)
print(ans)