-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredundantConnectionII.cpp
More file actions
53 lines (47 loc) · 1.46 KB
/
redundantConnectionII.cpp
File metadata and controls
53 lines (47 loc) · 1.46 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
52
53
// Source: https://leetcode.com/problems/redundant-connection-ii/
// Author: Miao Zhang
// Date: 2021-03-01
class Solution {
public:
vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {
vector<int> parents(edges.size() + 1, 0);
vector<int> roots(edges.size() + 1, 0);
vector<int> sizes(edges.size() + 1, 1);
vector<int> ans1;
vector<int> ans2;
for (auto& edge: edges) {
int u = edge[0];
int v = edge[1];
if (parents[v] > 0) {
ans1 = {parents[v], v};
ans2 = edge;
edge[0], edge[1] = -1;
}
parents[v] = u;
}
for (const auto& edge: edges) {
int u = edge[0];
int v = edge[1];
if (u < 0 || v < 0) continue;
if (!roots[u]) roots[u] = u;
if (!roots[v]) roots[v] = v;
int pu = find(u, roots);
int pv = find(v, roots);
if (pu == pv) {
return ans1.empty() ? edge: ans1;
}
if (sizes[pv] > sizes[pu]) swap(pu, pv);
roots[pv] = pu;
sizes[pu] += sizes[pv];
}
return ans2;
}
private:
int find(int node, vector<int>& roots) {
while (roots[node] != node) {
roots[node] = roots[roots[node]];
node = roots[node];
}
return node;
}
};