-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
minimum-edge-reversals-so-every-node-is-reachable.py
67 lines (60 loc) · 1.75 KB
/
minimum-edge-reversals-so-every-node-is-reachable.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
# Time: O(n)
# Space: O(n)
# iterative dfs, tree dp
class Solution(object):
def minEdgeReversals(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: List[int]
"""
def iter_dfs1():
result = 0
stk = [(0, -1)]
while stk:
u, p = stk.pop()
for v in adj[u].iterkeys():
if v == p:
continue
result += adj[u][v]
stk.append((v, u))
return result
def iter_dfs2(curr):
result = [-1]*n
stk = [(0, curr)]
while stk:
u, curr = stk.pop()
result[u] = curr
for v in adj[u].iterkeys():
if result[v] == -1:
stk.append((v, curr-adj[u][v]+adj[v][u]))
return result
adj = collections.defaultdict(dict)
for u, v in edges:
adj[u][v] = 0
adj[v][u] = 1
return iter_dfs2(iter_dfs1())
# Time: O(n)
# Space: O(n)
# dfs, tree dp
class Solution2(object):
def minEdgeReversals(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: List[int]
"""
def dfs1(u, p):
return sum(adj[u][v]+dfs1(v, u) for v in adj[u] if v != p)
def dfs2(u, curr):
result[u] = curr
for v in adj[u]:
if result[v] == -1:
dfs2(v, curr-adj[u][v]+adj[v][u])
adj = collections.defaultdict(dict)
for u, v in edges:
adj[u][v] = 0
adj[v][u] = 1
result = [-1]*n
dfs2(0, dfs1(0, -1))
return result