-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDisjoint_Set_Union.cpp
More file actions
78 lines (68 loc) · 1.53 KB
/
Disjoint_Set_Union.cpp
File metadata and controls
78 lines (68 loc) · 1.53 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Implementation of Union Find / Union by rank
//
// Running Time Complexity
// Initialize : O(N)
// Query : O(α(n)) , where α(n) is the inverse Ackermann function
#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
#define int long long
#define pii pair<int, int>
const int N = 100005;
int V;
int A[N], sz[N];
void initialize(int N)
{
for (int i = 1; i <= N; i++)
{
A[i] = i;
sz[i] = 1;
}
}
int get_parent(int node)
{
if(A[node] != node)
A[node] = get_parent(A[node]);
return A[node];
}
void merge(int u, int v)
{
int root_u = get_parent(u);
int root_v = get_parent(v);
if(sz[root_u] < sz[root_v])
{
A[root_u] = root_v;
sz[root_v] += sz[root_u];
}
else
{
A[root_v] = root_u;
sz[root_u] += sz[root_v];
}
}
int32_t main()
{
int Q, type, u, v;
cout << "Enter the no of elements:";
cin >> V;
initialize(V);
cout << "Enter the no of queries:";
cin >> Q;
while (Q--)
{
cin >> type >> u >> v;
if(type == 1) // Merge 2 nodes, u and v
{
merge(u, v);
cout << "Merged " << u << " and " << v << endl;
}
else if(type == 2) // Check if u and v are connected or not
{
if(get_parent(u) == get_parent(v))
cout << "Node " << u << " and " << v << " are connected";
else
cout << "Node " << u << " and " << v << " are not connected";
}
}
return 0;
}