-
Notifications
You must be signed in to change notification settings - Fork 364
/
DisjoinSetUnion.cpp
83 lines (68 loc) · 1.6 KB
/
DisjoinSetUnion.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <bits/stdc++.h>
using namespace std;
int parent[1000000];
// Find the topmost parent of a vertex
int root(int a)
{
if (a == parent[a]) {
return a;
}
return parent[a] = root(parent[a]);
}
// Connect two components by updating their parent
void connect(int a, int b)
{
a = root(a);
b = root(b);
if (a != b) {
parent[b] = a;
}
}
// Count the number of connected components
void connectedComponents(int n)
{
set<int> s;
for (int i = 0; i < n; i++) {
s.insert(root(parent[i]));
}
cout << "Number of connected components: " << s.size() << '\n';
}
// Print the input and call the functions
void printAnswer(int N, vector<vector<int>> edges)
{
// Initialize each vertex as its own parent
for (int i = 0; i <= N; i++) {
parent[i] = i;
}
// Connect the edges
for (int i = 0; i < edges.size(); i++) {
connect(edges[i][0], edges[i][1]);
}
// Print the number of connected components
connectedComponents(N);
}
int main()
{
int N;
cout << "Enter the number of vertices: ";
cin >> N;
vector<vector<int>> edges;
int m;
cout << "Enter the number of edges: ";
cin >> m;
cout << "Enter the edges:\n";
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
edges.push_back({u, v});
}
cout << "\nInput:\n";
cout << "Number of vertices: " << N << '\n';
cout << "Edges:\n";
for (int i = 0; i < m; i++) {
cout << edges[i][0] << " " << edges[i][1] << '\n';
}
cout << "\nOutput:\n";
printAnswer(N, edges);
return 0;
}