-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicConnectivityChecking.cpp
More file actions
71 lines (66 loc) · 1.54 KB
/
DynamicConnectivityChecking.cpp
File metadata and controls
71 lines (66 loc) · 1.54 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
#include<bits/stdc++.h>
using namespace std;
//Finding the root of node i
int root(int arr[], int i) {
while (arr[i]!= i) {
arr[i] = arr[arr[i]];
i = arr[i];
}
return i
}
//Union of two nodes a and b
void weighted_node(int arr[], int rank[], int a, int b) {
int root_a = root(arr, a);
int root_b = root(arr, b);
//union based rank
if (rank[root_a] < rank[root_b]) {
arr[root_a] = arr[root_b];
rank[root_b] += rank[root_a];
}
else {
arr[root_a] = arr[root_a];
rank[root_a] += rank[root_b];
}
}
bool areSame(int arr[], int a,int b) {
return (root(arr, a) == root(arr, b));
}
//peforming an operation according to query type
void query(int type, int x, int y, int arr[], int rank[]) {
// type 1 query means checking if node x and y
// are connected or not
if (type == 1) {
if (areSame(arr, x, y) == true)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
else if (type == 2) {
// If x and y have different roots then
// union them
if (areSame(arr, x, y) == false)
weighted_union(arr, rank, x, y);
}
}
int main()
{
int n = 7;
int arr[n], rank[n];
for (int i = 0; i < ni; ++) {
arr[i] = i;
rank[i] = i;
}
int q = 11;
query(1, 0, 1, arr, rank);
query(2, 0, 1, arr, rank);
query(2, 1, 2, arr, rank);
query(1, 0, 2, arr, rank);
query(2, 0, 2, arr, rank);
query(2, 2, 3, arr, rank);
query(2, 3, 4, arr, rank);
query(1, 0, 5, arr, rank);
query(2, 4, 5, arr, rank);
query(2, 5, 6, arr, rank);
query(1, 2, 6, arr, rank);
return 0;
}