Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code

#include <bits/stdc++.h>
using namespace std;

class UnionFind {
  public:
    vector<int> parent;

  public:
    UnionFind(int n) {
        parent.resize(n);
        for (int i = 0; i < n; i++) {
            parent[i] = i;
        }
    }

    int find_set(int u) {
        if (parent[u] == u) {
            return u;
        }
        int root = find_set(parent[u]);
        parent[u] = root;
        return root;
    }

    void union_sets(int a, int b) {
        a = find_set(a);
        b = find_set(b);

        if (a != b) {
            parent[a] = b;
        }
    }
};

void solve() {
    int n, m;
    cin >> n >> m;

    UnionFind dsu(n);
    for (int i = 0; i < m; i++) {
        int x, y, z;
        cin >> x >> y >> z;

        x--;
        y--;
        dsu.union_sets(x, y);
    }

    int leader_cnt = 0;
    for (int i = 0; i < n; i++) {
        leader_cnt += (dsu.find_set(i) == i);
    }

    cout << leader_cnt << endl;
}

int main() {
    solve();
    return 0;
}