Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- #include <cstdio>
- #include <vector>
- #include <iostream>
- #include <algorithm>
- #include <unordered_map>
- #include <set>
- using namespace std;
- struct UnionFind {
- vector<int> parents;
- public:
- UnionFind(int count) : parents(count) {
- for (int i = 0; i < count; i++)
- {
- parents[i] = i;
- }
- }
- bool areInOneSet(int a, int b) {
- return getParent(a) == getParent(b);
- }
- int getParent(int idx) {
- if (parents[idx] == idx)
- {
- return idx;
- }
- return parents[idx] = getParent(parents[idx]);
- }
- void unite(int a, int b) {
- parents[getParent(a)] = getParent(b);
- }
- int countUniqueParents() {
- set<int> unique;
- for (size_t i = 0; i < parents.size(); i++)
- {
- unique.insert(parents[i] = getParent(i));
- }
- return unique.size();
- }
- };
- int main()
- {
- int t, x, y, a, b;
- cin >> t;
- vector<int> results;
- for (size_t i = 0; i < t; i++)
- {
- cin >> x >> y;
- UnionFind graph(x);
- for (size_t j = 0; j < y; j++)
- {
- cin >> a >> b;
- graph.unite(a, b);
- }
- results.push_back(graph.countUniqueParents());
- }
- for (auto num : results) {
- cout << num << " ";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment