36uint32_t number_of_nodes = 0;
37std::vector<int64_t> parent{};
38std::vector<uint32_t> connected_set_size{};
44 for (uint32_t i = 1; i <= number_of_nodes; i++) {
46 connected_set_size[i] = 1;
55 while (parent[val] != val) {
56 parent[val] = parent[parent[val]];
73 if (connected_set_size[node1] < connected_set_size[node2]) {
74 std::swap(node1, node2);
76 parent[node2] = node1;
77 connected_set_size[node1] +=
78 connected_set_size[node2];
86 std::set<int64_t> temp;
87 for (uint32_t i = 1; i <= number_of_nodes; i++) temp.insert(
find_set(i));
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);
106 int64_t node_a = 0, node_b = 0;
107 std::cin >> node_a >> node_b;
108 dsu::union_sets(node_a, node_b);
110 std::cout << dsu::no_of_connected_components() << std::endl;
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.
void make_set()
function the initialize every node as it's own parent
Functions for Disjoint union implementation.