-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsoln-1.cpp
40 lines (36 loc) · 873 Bytes
/
soln-1.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
auto desyncio = []()
{
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
const int N = 1003;
int parent[N] = {0};
int sizes[N] = {0};
int find(int x) {
return parent[x] == x ? x : parent[x] = find(parent[x]);
}
void unite(int x, int y) {
int rx = find(x);
int ry = find(y);
if (rx == ry) return;
if (sizes[y] < sizes[x]) swap(x, y);
parent[rx] = parent[ry];
sizes[ry] += sizes[rx];
}
class Solution {
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
for(int i = 0; i < N; ++i) {
parent[i] = i;
sizes[i] = 1;
}
for(auto & edge : edges) {
int u = edge[0], v = edge[1];
int ru = find(u), rv = find(v);
if (ru == rv) return {u, v};
unite(ru, rv);
}
return {};
}
};