-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path1101.cpp
More file actions
50 lines (50 loc) · 1.17 KB
/
1101.cpp
File metadata and controls
50 lines (50 loc) · 1.17 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
class DisjointSet {
private:
vector<int> parent;
vector<int> rank;
int groups = 0;
public:
DisjointSet(int size) {
parent.resize(size, 0);
rank.resize(size, 0);
for (int i = 0; i < size; ++i) parent[i] = i;
groups = size;
}
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void join(int x, int y) {
int pX = find(x);
int pY = find(y);
if (pX == pY) return;
groups--;
if (rank[pX] > rank[pY]) {
parent[pY] = pX;
}
else if (rank[pX] < rank[pY]) {
parent[pX] = pY;
}
else {
parent[pY] = pX;
rank[pX]++;
}
}
bool isAllConnected() {
return groups == 1;
}
};
class Solution {
public:
int earliestAcq(vector<vector<int>>& logs, int n) {
DisjointSet* disjointSet = new DisjointSet(n);
sort(logs.begin(), logs.end());
for (auto& log : logs) {
disjointSet->join(log[1], log[2]);
if (disjointSet->isAllConnected()) return log[0];
}
return -1;
}
};