2020-05-22 01:59:52 +08:00
|
|
|
#include <iostream>
|
|
|
|
#include <set>
|
2020-06-20 00:04:56 +08:00
|
|
|
#include <vector>
|
2020-05-22 01:59:52 +08:00
|
|
|
|
2020-08-08 00:49:12 +08:00
|
|
|
int number_of_nodes; // denotes number of nodes;
|
2020-05-22 03:36:40 +08:00
|
|
|
std::vector<int> parent;
|
2020-08-08 00:49:12 +08:00
|
|
|
std::vector<int> connected_set_size;
|
2020-05-22 01:59:52 +08:00
|
|
|
void make_set() { // function the initialize every node as it's own parent
|
2020-08-08 00:49:12 +08:00
|
|
|
for (int i = 1; i <= number_of_nodes; i++) {
|
2020-05-22 01:59:52 +08:00
|
|
|
parent[i] = i;
|
2020-08-08 00:49:12 +08:00
|
|
|
connected_set_size[i] = 1;
|
2020-05-22 01:59:52 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// To find the component where following node belongs to
|
|
|
|
int find_set(int v) {
|
2020-08-08 00:49:12 +08:00
|
|
|
if (v == parent[v]) {
|
2020-05-22 01:59:52 +08:00
|
|
|
return v;
|
2020-08-08 00:49:12 +08:00
|
|
|
}
|
2020-05-22 01:59:52 +08:00
|
|
|
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) {
|
2020-08-08 00:49:12 +08:00
|
|
|
if (connected_set_size[a] < connected_set_size[b]) {
|
2020-05-22 01:59:52 +08:00
|
|
|
std::swap(a, b);
|
2020-08-08 00:49:12 +08:00
|
|
|
}
|
2020-05-22 01:59:52 +08:00
|
|
|
parent[b] = a;
|
2020-08-08 00:49:12 +08:00
|
|
|
connected_set_size[a] += connected_set_size[b];
|
2020-05-22 01:59:52 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
int no_of_connected_components() { // To find total no of connected components
|
|
|
|
std::set<int> temp; // temp set to count number of connected components
|
2020-08-08 00:49:12 +08:00
|
|
|
for (int i = 1; i <= number_of_nodes; i++) temp.insert(find_set(i));
|
2020-05-22 01:59:52 +08:00
|
|
|
return temp.size();
|
|
|
|
}
|
|
|
|
|
|
|
|
// All critical/corner cases have been taken care of.
|
|
|
|
// Input your required values: (not hardcoded)
|
2020-05-22 03:19:03 +08:00
|
|
|
int main() {
|
2020-08-08 00:49:12 +08:00
|
|
|
std::cin >> number_of_nodes;
|
|
|
|
parent.resize(number_of_nodes + 1);
|
|
|
|
connected_set_size.resize(number_of_nodes + 1);
|
2020-05-22 01:59:52 +08:00
|
|
|
make_set();
|
2020-08-08 00:49:12 +08:00
|
|
|
int edges = 0;
|
2020-05-22 01:59:52 +08:00
|
|
|
std::cin >> edges; // no of edges in the graph
|
|
|
|
while (edges--) {
|
2020-08-08 00:49:12 +08:00
|
|
|
int node_a = 0, node_b = 0;
|
2020-05-22 01:59:52 +08:00
|
|
|
std::cin >> node_a >> node_b;
|
|
|
|
union_sets(node_a, node_b);
|
|
|
|
}
|
|
|
|
std::cout << no_of_connected_components() << std::endl;
|
|
|
|
return 0;
|
|
|
|
}
|