-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDSU.cpp
More file actions
51 lines (46 loc) · 1.08 KB
/
DSU.cpp
File metadata and controls
51 lines (46 loc) · 1.08 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
#include <vector>
class UnionFind {
private:
std::vector<int> parent;
std::vector<int> size;
public:
UnionFind(int n) {
parent.resize(n);
size.resize(n, 1);
for (int i = 0; i < n; ++i) {
parent[i] = i;
}
}
int find(int x) {
if (parent[x] == x) {
return x; // Path compression
}
return parent[x] = find(parent[x]);
}
bool unite(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY) {
return false;
}
if (size[rootX] < size[rootY]) {
std::swap(rootX, rootY);
}
parent[rootY] = rootX;
size[rootX] += size[rootY];
return true;
}
};
class Solution {
public:
std::vector<int> findRedundantConnection(std::vector<std::vector<int>>& edges) {
int n = edges.size();
UnionFind uf(n);
for (const auto& edge : edges) {
if (!uf.unite(edge[0] - 1, edge[1] - 1)) {
return edge;
}
}
return {};
}
};