-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution2.cpp
67 lines (63 loc) · 1.6 KB
/
Solution2.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class UnionFind {
public:
UnionFind(int n) {
p = vector<int>(n);
size = vector<int>(n, 1);
iota(p.begin(), p.end(), 0);
}
bool unite(int a, int b) {
int pa = find(a), pb = find(b);
if (pa == pb) {
return false;
}
if (size[pa] > size[pb]) {
p[pb] = pa;
size[pa] += size[pb];
} else {
p[pa] = pb;
size[pb] += size[pa];
}
return true;
}
int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
private:
vector<int> p, size;
};
class Solution {
public:
vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {
int n = edges.size();
vector<int> ind(n);
for (const auto& e : edges) {
++ind[e[1] - 1];
}
vector<int> dup;
for (int i = 0; i < n; ++i) {
if (ind[edges[i][1] - 1] == 2) {
dup.push_back(i);
}
}
UnionFind uf(n);
if (!dup.empty()) {
for (int i = 0; i < n; ++i) {
if (i == dup[1]) {
continue;
}
if (!uf.unite(edges[i][0] - 1, edges[i][1] - 1)) {
return edges[dup[0]];
}
}
return edges[dup[1]];
}
for (int i = 0;; ++i) {
if (!uf.unite(edges[i][0] - 1, edges[i][1] - 1)) {
return edges[i];
}
}
}
};