-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathcount-pairs-of-connectable-servers-in-a-weighted-tree-network.py
107 lines (99 loc) · 3.01 KB
/
count-pairs-of-connectable-servers-in-a-weighted-tree-network.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
106
107
# Time: O(n^2)
# Space: O(n)
# iterative dfs
class Solution(object):
def countPairsOfConnectableServers(self, edges, signalSpeed):
"""
:type edges: List[List[int]]
:type signalSpeed: int
:rtype: List[int]
"""
def iter_dfs(u, p, dist):
result = 0
stk = [(u, p, dist)]
while stk:
u, p, dist = stk.pop()
if dist%signalSpeed == 0:
result += 1
for v, w in reversed(adj[u]):
if v == p:
continue
stk.append((v, u, dist+w))
return result
adj = [[] for _ in xrange(len(edges)+1)]
for u, v, w in edges:
adj[u].append((v, w))
adj[v].append((u, w))
result = [0]*(len(edges)+1)
for u in xrange(len(result)):
curr = 0
for v, w in adj[u]:
cnt = iter_dfs(v, u, w)
result[u] += curr*cnt
curr += cnt
return result
# Time: O(n^2)
# Space: O(n)
# dfs
class Solution2(object):
def countPairsOfConnectableServers(self, edges, signalSpeed):
"""
:type edges: List[List[int]]
:type signalSpeed: int
:rtype: List[int]
"""
def dfs(u, p, dist):
cnt = 1 if dist%signalSpeed == 0 else 0
for v, w in adj[u]:
if v == p:
continue
cnt += dfs(v, u, dist+w)
return cnt
adj = [[] for _ in xrange(len(edges)+1)]
for u, v, w in edges:
adj[u].append((v, w))
adj[v].append((u, w))
result = [0]*(len(edges)+1)
for u in xrange(len(result)):
curr = 0
for v, w in adj[u]:
cnt = dfs(v, u, w)
result[u] += curr*cnt
curr += cnt
return result
# Time: O(n^2)
# Space: O(n)
# bfs
class Solution3(object):
def countPairsOfConnectableServers(self, edges, signalSpeed):
"""
:type edges: List[List[int]]
:type signalSpeed: int
:rtype: List[int]
"""
def bfs(u, p, dist):
result = 0
q = [(u, p, dist)]
while q:
new_q = []
for u, p, dist in q:
if dist%signalSpeed == 0:
result += 1
for v, w in adj[u]:
if v == p:
continue
new_q.append((v, u, dist+w))
q = new_q
return result
adj = [[] for _ in xrange(len(edges)+1)]
for u, v, w in edges:
adj[u].append((v, w))
adj[v].append((u, w))
result = [0]*(len(edges)+1)
for u in xrange(len(result)):
curr = 0
for v, w in adj[u]:
cnt = bfs(v, u, w)
result[u] += curr*cnt
curr += cnt
return result