-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindRedundantConnection.cpp
More file actions
43 lines (40 loc) · 1.08 KB
/
findRedundantConnection.cpp
File metadata and controls
43 lines (40 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
class Solution {
public:
struct UF{
vector<int> id, size;
UF(int n): id(vector<int>(n, 0)), size(vector<int>(n, 1)) {
iota(id.begin(), id.end(), 0);
}
int find(int p) {
int cur = p;
while (cur != id[cur])
cur = id[cur];
while (p != id[p]) {
int temp = id[p];
id[p] = cur;
p = temp;
}
return cur;
}
void connect(int p, int q) {
int x = find(p), y = find(q);
if (x == y) return;
if (size[x] > size[y]) swap(x, y);
id[x] = y;
size[y] += size[x];
}
bool isConnected(int p, int q) {
return find(p) == find(q);
}
};
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
int n = edges.size();
UF uf(n + 1);
for (auto e: edges) {
int u = e[0], v = e[1];
if (uf.isConnected(u, v)) return e;
uf.connect(u, v)
}
return {-1, -1};
}
};