TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
connected_components_with_dsu.cpp
Go to the documentation of this file.
1
20#include <cstdint>
21#include <iostream>
22#include <set>
23#include <vector>
24
29namespace graph {
35namespace disjoint_union {
36uint32_t number_of_nodes = 0; // denotes number of nodes
37std::vector<int64_t> parent{}; // parent of each node
38std::vector<uint32_t> connected_set_size{}; // size of each set
43void make_set() {
44 for (uint32_t i = 1; i <= number_of_nodes; i++) {
45 parent[i] = i;
46 connected_set_size[i] = 1;
47 }
48}
54int64_t find_set(int64_t val) {
55 while (parent[val] != val) {
56 parent[val] = parent[parent[val]];
57 val = parent[val];
58 }
59 return val;
60}
67void union_sets(int64_t node1, int64_t node2) {
68 node1 = find_set(node1); // find the parent of node1
69 node2 = find_set(node2); // find the parent of node2
70
71 // If parents of both nodes are not same, combine them
72 if (node1 != node2) {
73 if (connected_set_size[node1] < connected_set_size[node2]) {
74 std::swap(node1, node2); // swap both components
75 }
76 parent[node2] = node1; // make node1 as parent of node2.
77 connected_set_size[node1] +=
78 connected_set_size[node2]; // sum the size of both as they combined
79 }
80}
86 std::set<int64_t> temp; // temp set to count number of connected components
87 for (uint32_t i = 1; i <= number_of_nodes; i++) temp.insert(find_set(i));
88 return temp.size(); // return the size of temp set
89}
90} // namespace disjoint_union
91} // namespace graph
92
97static void test() {
98 namespace dsu = graph::disjoint_union;
99 std::cin >> dsu::number_of_nodes;
100 dsu::parent.resize(dsu::number_of_nodes + 1);
101 dsu::connected_set_size.resize(dsu::number_of_nodes + 1);
102 dsu::make_set();
103 uint32_t edges = 0;
104 std::cin >> edges; // no of edges in the graph
105 while (edges--) {
106 int64_t node_a = 0, node_b = 0;
107 std::cin >> node_a >> node_b;
108 dsu::union_sets(node_a, node_b);
109 }
110 std::cout << dsu::no_of_connected_components() << std::endl;
111}
112
117int main() {
118 test(); // Execute the tests
119 return 0;
120}
Disjoint sets union data structure, class based representation.
int64_t find_set(int64_t val)
Find the component where following node belongs to.
void union_sets(int64_t node1, int64_t node2)
Merge 2 components to become one.
static void test()
Test Implementations.
uint32_t no_of_connected_components()
Find total no. of connected components.
int main()
Main function.
void make_set()
function the initialize every node as it's own parent
Functions for Disjoint union implementation.
Graph Algorithms.