-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path952.cpp
More file actions
72 lines (69 loc) · 1.72 KB
/
952.cpp
File metadata and controls
72 lines (69 loc) · 1.72 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
71
72
class DisjointSetUnion{
public:
vector<int> parent;
vector<int> rank;
int mx;
DisjointSetUnion(int V){
mx = 1;
parent.resize(V+1);
rank.resize(V+1);
for(int i=0;i<=V;i++){
parent[i] = i;
rank[i] = 1;//for size of tree start with 1 instead of 0
}
}
int Find(int u){
if(u != parent[u])
parent[u] = Find(parent[u]);
return parent[u];
}
void Union(int u, int v){
u = Find(u);
v = Find(v);
if(u==v)
return;
if(rank[u]<rank[v])//same for size
swap(u,v);
parent[v] = u;
// if(rank[u]==rank[v])//do not check simply size[a] += size[b];
rank[u] += rank[v];
mx = max(rank[u],mx);
return;
}
};
class Solution {
public:
int N = 20001;
int largestComponentSize(vector<int>& A) {
int n = A.size();
DisjointSetUnion ds(N);
unordered_map<int,int> ump;
int res = 0;
for(int i=0; i<n; i++){
int x = A[i];
for(int j=2; j*j<=x; j++){
if(x%j==0){
if(ump.count(j)){
ds.Union(ump[j],i);
}
else{
ump[j] = i;
}
if(ump.count(x/j)){
ds.Union(ump[x/j],i);
}
else{
ump[x/j] = i;
}
}
}
if(ump.count(x)){
ds.Union(ump[x],i);
}
else{
ump[x] = i;
}
}
return ds.mx;
}
};