forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree-of-coprimes.py
93 lines (84 loc) · 2.96 KB
/
tree-of-coprimes.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
# Time: O(50 * n) = O(n)
# Space: O(n)
import collections
import fractions
class Solution(object):
def getCoprimes(self, nums, edges):
"""
:type nums: List[int]
:type edges: List[List[int]]
:rtype: List[int]
"""
def iter_dfs(nums, adj):
result = [-1]*len(nums)
path = collections.defaultdict(list)
stk = [(1, (-1, 0, 0))]
while stk:
step, params = stk.pop()
if step == 1:
prev, node, depth = params
stk.append((4, (node,)))
stk.append((3, (prev, node, depth)))
stk.append((2, (node,)))
elif step == 2:
node = params[0]
max_d = -1
for x in path.iterkeys():
if fractions.gcd(nums[node], x) != 1:
continue
if path[x][-1][1] > max_d:
max_d = path[x][-1][1]
result[node] = path[x][-1][0]
elif step == 3:
prev, node, depth = params
path[nums[node]].append((node, depth))
for nei in adj[node]:
if nei == prev:
continue
stk.append((1, (node, nei, depth+1)))
elif step == 4:
node = params[0]
path[nums[node]].pop()
if not path[nums[node]]:
path.pop(nums[node])
return result
adj = collections.defaultdict(list)
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
return iter_dfs(nums, adj)
# Time: O(50 * n) = O(n)
# Space: O(n)
import collections
import fractions
class Solution2(object):
def getCoprimes(self, nums, edges):
"""
:type nums: List[int]
:type edges: List[List[int]]
:rtype: List[int]
"""
def dfs(nums, adj, prev, node, depth, path, result):
max_d = -1
for x in path.iterkeys():
if fractions.gcd(nums[node], x) != 1:
continue
if path[x][-1][1] > max_d:
max_d = path[x][-1][1]
result[node] = path[x][-1][0]
path[nums[node]].append((node, depth))
for nei in adj[node]:
if nei == prev:
continue
dfs(nums, adj, node, nei, depth+1, path, result)
path[nums[node]].pop()
if not path[nums[node]]:
path.pop(nums[node])
adj = collections.defaultdict(list)
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
result = [-1]*len(nums)
path = collections.defaultdict(list)
dfs(nums, adj, -1, 0, 0, path, result)
return result