-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path2709-greatest-common-divisor-traversal.py
45 lines (41 loc) · 1.29 KB
/
2709-greatest-common-divisor-traversal.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
class UnionFind:
def __init__(self, n):
self.par = [i for i in range(n)]
self.size = [1] * n
self.count = n
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
px, py = self.find(x), self.find(y)
if px == py:
return
if self.size[px] < self.size[py]:
self.par[px] = py
self.size[py] += self.size[px]
else:
self.par[py] = px
self.size[px] += self.size[py]
self.count -=1
class Solution:
def canTraverseAllPairs(self, nums: List[int]) -> bool:
uf = UnionFind(len(nums))
factor_index = {}
for i, n in enumerate(nums):
f = 2
while f * f <= n:
if n % f == 0:
if f in factor_index:
uf.union(i, factor_index[f])
else:
factor_index[f] = i
while n % f == 0:
n = n // f
f += 1
if n > 1:
if n in factor_index:
uf.union(i, factor_index[n])
else:
factor_index[n] = i
return uf.count == 1