File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ class UnionFind :
2
+ def __init__ (self , n ):
3
+ self .par = [i for i in range (n )]
4
+ self .size = [1 ] * n
5
+ self .count = n
6
+
7
+ def find (self , x ):
8
+ if self .par [x ] != x :
9
+ self .par [x ] = self .find (self .par [x ])
10
+ return self .par [x ]
11
+
12
+ def union (self , x , y ):
13
+ px , py = self .find (x ), self .find (y )
14
+ if px == py :
15
+ return
16
+ if self .size [px ] < self .size [py ]:
17
+ self .par [px ] = py
18
+ self .size [py ] += self .size [px ]
19
+ else :
20
+ self .par [py ] = px
21
+ self .size [px ] += self .size [py ]
22
+ self .count -= 1
23
+
24
+ class Solution :
25
+ def canTraverseAllPairs (self , nums : List [int ]) -> bool :
26
+ uf = UnionFind (len (nums ))
27
+
28
+ factor_index = {}
29
+ for i , n in enumerate (nums ):
30
+ f = 2
31
+ while f * f <= n :
32
+ if n % f == 0 :
33
+ if f in factor_index :
34
+ uf .union (i , factor_index [f ])
35
+ else :
36
+ factor_index [f ] = i
37
+ while n % f == 0 :
38
+ n = n // f
39
+ f += 1
40
+ if n > 1 :
41
+ if n in factor_index :
42
+ uf .union (i , factor_index [n ])
43
+ else :
44
+ factor_index [n ] = i
45
+ return uf .count == 1
You can’t perform that action at this time.
0 commit comments