-
Notifications
You must be signed in to change notification settings - Fork 3
/
261.cpp
43 lines (43 loc) · 1.1 KB
/
261.cpp
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
class DisjointSet {
private:
vector<int> parent;
vector<int> rank;
public:
DisjointSet(int size) {
parent.resize(size, 0);
rank.resize(size, 0);
for (int i = 0; i < size; i++) parent[i] = i;
}
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
bool join(int x, int y) {
int pX = find(x);
int pY = find(y);
if (pX == pY) return false;
if (rank[pX] > rank[pY]) parent[pY] = pX;
else if (rank[pX] < rank[pY]) parent[pX] = pY;
else {
parent[pY] = pX;
rank[pX]++;
}
return true;
}
};
class Solution {
public:
bool validTree(int n, vector<vector<int>>& edges) {
DisjointSet* disjointSet = new DisjointSet(n);
for (auto edge : edges) {
if (!disjointSet->join(edge[0], edge[1])) return false;
}
int parent = disjointSet->find(0);
for (int i = 1; i < n; i++) {
if (disjointSet->find(i) != parent) return false;
}
return true;
}
};