-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunion_find.cpp
52 lines (51 loc) · 1.13 KB
/
union_find.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
class Solution {
public:
vector<int> arr;
int findParent(int x)
{
if(arr[x] < 0)
return x;
else
{
int y= x;
while(arr[x] > 0)
x=arr[x];
arr[y] = x;
}
return x;
}
void Union(int p1 , int p2)
{
if(arr[p1] <= arr[p2])
{
arr[p2] = p1;
arr[p1] = arr[p1] -2;
}
else
{
arr[p1] = p2;
arr[p2] = arr[p2] -2;
}
}
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
arr.resize(edges.size()+1,-1);
arr[0] = 0;
vector<int> res(2);
for (int i=0; i<edges.size(); i++)
{
for(int j=0; j<1;j++)
{
int p1 = findParent(edges[i][j]);
int p2 = findParent(edges[i][j+1]);
if(p1 == p2)
{
res[0]= edges[i][j];
res[1] = edges[i][j+1];
}
else
Union(p1,p2);
}
}
return res;
}
};