-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgcdTraversal.java
More file actions
70 lines (54 loc) · 1.61 KB
/
gcdTraversal.java
File metadata and controls
70 lines (54 loc) · 1.61 KB
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
class Solution {
class DSU {
int[] parent;
DSU(int n) {
parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
}
int find(int x) {
if (parent[x] != x)
parent[x] = find(parent[x]);
return parent[x];
}
void union(int a, int b) {
int pa = find(a), pb = find(b);
if (pa != pb) parent[pa] = pb;
}
}
public boolean canTraverseAllPairs(int[] nums) {
int n = nums.length;
if (n == 1) return true;
for (int num : nums) {
if (num == 1) return false;
}
DSU dsu = new DSU(n);
Map<Integer, Integer> factorMap = new HashMap<>();
for (int i = 0; i < n; i++) {
int num = nums[i];
for (int f = 2; f * f <= num; f++) {
if (num % f == 0) {
if (factorMap.containsKey(f)) {
dsu.union(i, factorMap.get(f));
} else {
factorMap.put(f, i);
}
while (num % f == 0) {
num /= f;
}
}
}
if (num > 1) {
if (factorMap.containsKey(num)) {
dsu.union(i, factorMap.get(num));
} else {
factorMap.put(num, i);
}
}
}
int root = dsu.find(0);
for (int i = 1; i < n; i++) {
if (dsu.find(i) != root) return false;
}
return true;
}
}