-
Notifications
You must be signed in to change notification settings - Fork 6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add_edge -> increase_capacity #5
Comments
Here’s the code with capacity scaling. This solves from typing import List, Dict, Optional, Set
from collections import defaultdict
class FordFulkersonDFS:
def __init__(self, n):
self.G: List[Dict[int, int]] = [
defaultdict(int) for _ in range(n)
] # neighbourhood dict, N[u] = {v_1: cap_1, v_2: cap_2, ...}
self.S: Set[int] = set() # redundant
def add_edge(self, u, v, w):
""" Add edge (u,v,w): u->v with weight w """
self.G[u][v] += w
def find_flow(self, source: int, to: int) -> int:
def dfs(u: int, hi: int) -> Optional[int]: # nonzero
G = self.G
S = self.S
if u in S:
return None
if u == to:
return hi
S.add(u)
for v, cap in G[u].items():
if cap > lo:
f = dfs(v, min(hi, cap))
if f:
G[u][v] -= f
G[v][u] += f
return f
return None
flow = 0
hi = 10 ** 9 # MAXCAP
lo = hi // 2
while True:
self.S = set()
pushed = dfs(s, hi)
if not pushed:
if lo == 0:
break
else:
lo //= 2
else:
flow += pushed
return flow |
Please have a look at e35d589, it incorporates most of your proposed changes, but I didn't like |
Your while loop is much better. I think this whole thing came out great.
|
I let Btw, I previously solved mincut with a Dijkstra instead of scaling edges. (Not using the heapkey |
This just bit me in the ass when I solved
elementarymath
(and added the “same” edge twice). The chanced name avoids this mistake, I think.notebook/code/Graphs/flow.py
Line 6 in c05317b
Also,
dfs
can be made local tomax_flow
. This again saves some typing and makes the structure clearer:The text was updated successfully, but these errors were encountered: