File tree 1 file changed +104
-0
lines changed
1 file changed +104
-0
lines changed Original file line number Diff line number Diff line change
1
+ typedef vector<int > vi;
2
+
3
+ struct dsu {
4
+ vector<int > parent;
5
+ vector<int > _size;
6
+
7
+ // merge two sets having a&b as entities
8
+ void union_sets (int a, int b) {
9
+ a = find_set (a);
10
+ b = find_set (b);
11
+ if (a != b) {
12
+ if (_size[a] < _size[b])
13
+ swap (a, b);
14
+ parent[b] = a;
15
+ _size[a] += _size[b];
16
+ }
17
+ }
18
+
19
+ // find the set leader
20
+ int find_set (int v) {
21
+ if (v == parent[v])
22
+ return v;
23
+ return parent[v] = find_set (parent[v]);
24
+ }
25
+
26
+ // check if same set/leader
27
+ bool same_comp (int a, int b) {
28
+ return find_set (a) == find_set (b);
29
+ }
30
+
31
+ void make_set (int v) {
32
+ parent[v] = v;
33
+ _size[v] = 1 ;
34
+ }
35
+
36
+ void _init (int n) {
37
+ parent.assign (n, 0 );
38
+ _size.assign (n, 0 );
39
+
40
+ for (int i = 0 ; i < n; i++)
41
+ make_set (i);
42
+ }
43
+ };
44
+
45
+ class Solution
46
+ {
47
+ public:
48
+ vector<int > findRedundantDirectedConnection (vector<vector<int >>& edges) {
49
+ int edgeParent = -1 ;
50
+ int edgeCycle = -1 ;
51
+
52
+ int n = edges.size ();
53
+
54
+ // 1. check for dual parent edge
55
+ vi par (n + 1 , 0 );
56
+ for (int i = 0 ; i < n; i++) {
57
+ auto e = edges[i];
58
+ int a = e[0 ];
59
+ int b = e[1 ];
60
+ // a -> b
61
+ if (par[b])
62
+ {
63
+ // c -> b
64
+ edgeParent = i;
65
+ break ;
66
+ }
67
+ else {
68
+ par[b] = a;
69
+ }
70
+ }
71
+
72
+ // 2. check for cycle after removing the dual parent edge
73
+ dsu G;
74
+ G._init (n + 1 );
75
+ for (int i = 0 ; i < n; ++i) {
76
+ if (i == edgeParent) continue ;
77
+ auto e = edges[i];
78
+ int a = e[0 ];
79
+ int b = e[1 ];
80
+
81
+ if (G.find_set (a) != G.find_set (b))
82
+ G.union_sets (a, b);
83
+ else {
84
+ edgeCycle = i;
85
+ break ;
86
+ }
87
+ }
88
+
89
+ // if no 2nd parent,
90
+ if (edgeParent == -1 ){
91
+ return edges[edgeCycle];
92
+ }
93
+
94
+ // if 2nd parent, but the wrong edge
95
+ if (edgeCycle != -1 ){
96
+ int to = edges[edgeParent][1 ];
97
+ int p = par[to];
98
+ return {p, to};
99
+ }
100
+
101
+ // the correct 2nd edge
102
+ return edges[edgeParent];
103
+ }
104
+ };
You can’t perform that action at this time.
0 commit comments