-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path3378.cpp
More file actions
60 lines (59 loc) · 1.53 KB
/
3378.cpp
File metadata and controls
60 lines (59 loc) · 1.53 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
class DisjointSet {
private:
vector<int> parents;
vector<int> ranks;
public:
DisjointSet(int n) {
parents.resize(n, 0);
for (int i = 0; i < n; ++i) parents[i] = i;
ranks.resize(n, 1);
}
int find(int x) {
if (parents[x] != x) {
parents[x] = find(parents[x]);
}
return parents[x];
}
void join(int x, int y) {
int pX = find(x);
int pY = find(y);
if (pX == pY) return;
if (ranks[pX] > ranks[pY]) {
parents[pY] = pX;
}
else if (ranks[pX] < ranks[pY]) {
parents[pX] = pY;
}
else {
parents[pY] = pX;
ranks[pX]++;
}
}
};
class Solution {
public:
int countComponents(vector<int>& nums, int threshold) {
unordered_set<int> visited;
DisjointSet* disjointSet = new DisjointSet(threshold + 1);
for (auto& num : nums) {
if (visited.count(num)) continue;
visited.insert(num);
for (int factor = 2; factor * num <= threshold; factor++) {
disjointSet->join(num, num * factor);
visited.insert(num * factor);
}
}
unordered_set<int> cnts;
for (auto& num : nums) {
if (num > threshold) {
cnts.insert(num);
}
else {
int group = disjointSet->find(num);
cnts.insert(group);
}
}
int res = cnts.size();
return res;
}
};