-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamicConnectivity.cpp
56 lines (52 loc) · 1.22 KB
/
dynamicConnectivity.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
#include <iostream>
#include <vector>
using namespace std;
class DSU {
vector<int> parent, rank;
int n;
public:
int sets = 0;
DSU(int _n){
n = _n;
parent.assign(n, -1);
rank.assign(n, 1);
sets = n;
}
int find(int x) {
if (parent[x] == -1) {
return x;
} else
return parent[x] = find(parent[x]);
}
void unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y) {
// already same set, no need
return;
}
if (rank[x] >= rank[y]){
parent[y] = x;
rank[x] += rank[y];
} else {
parent[x] = y;
rank[y] += rank[x];
}
sets--;
}
};
int main() {
int n, q;
cout<< "Enter number of nodes and number of addition queries: ";
cin >> n >> q;
DSU dsu(n);
cout<<"Number of connected components: "<< dsu.sets << endl;
for (int i = 0; i < q; i++) {
int u, v;
cout << "Enter the start and end index of edge:(0-indexed) ";
cin >> u >> v;
dsu.unite(u, v);
cout<<"Number of connected components after query "<< i+1 << ": "<<dsu.sets << endl;
}
return 0;
}