connected components with dsu Algorithm
Connected Components with DSU Algorithm refers to the process of identifying connected components in an undirected graph using Disjoint Set Union (DSU) data structure, which is also known as Union-Find. Connected components are the subsets of vertices in a graph where each vertex is reachable from any other vertex within the same subset. The DSU data structure is used to efficiently manage the connections between the vertices and determine which vertices belong to the same connected component. This data structure supports two primary operations: find and union. The find operation determines the representative element (or the parent) of a given element in a set, while the union operation merges two sets that contain the given elements, forming a new connected component.
The Connected Components with DSU Algorithm starts by initializing each vertex as its own parent, representing a separate connected component. Then, for each edge in the graph, the algorithm performs a find operation on both vertices of the edge. If the representative elements (parents) of both vertices are different, it means they belong to distinct connected components, and a union operation is performed to merge the two components. After processing all edges, the connected components can be determined by grouping vertices with the same representative element (parent). The algorithm's efficiency comes from the fact that union and find operations can be performed in nearly constant time using path compression and union by rank optimizations. This makes the Connected Components with DSU Algorithm suitable for analyzing large graphs and solving problems that require efficient handling of connected components.
#include <iostream>
#include <vector>
#include <set>
int N; // denotes number of nodes;
std::vector<int> parent;
std::vector<int> siz;
void make_set() { // function the initialize every node as it's own parent
for (int i = 1; i <= N; i++) {
parent[i] = i;
siz[i] = 1;
}
}
// To find the component where following node belongs to
int find_set(int v) {
if (v == parent[v])
return v;
return parent[v] = find_set(parent[v]);
}
void union_sets(int a, int b) { // To join 2 components to belong to one
a = find_set(a);
b = find_set(b);
if (a != b) {
if (siz[a] < siz[b])
std::swap(a, b);
parent[b] = a;
siz[a] += siz[b];
}
}
int no_of_connected_components() { // To find total no of connected components
std::set<int> temp; // temp set to count number of connected components
for (int i = 1; i <= N; i++)
temp.insert(find_set(i));
return temp.size();
}
// All critical/corner cases have been taken care of.
// Input your required values: (not hardcoded)
int main() {
std::cin >> N;
parent.resize(N + 1);
siz.resize(N + 1);
make_set();
int edges;
std::cin >> edges; // no of edges in the graph
while (edges--) {
int node_a, node_b;
std::cin >> node_a >> node_b;
union_sets(node_a, node_b);
}
std::cout << no_of_connected_components() << std::endl;
return 0;
}