Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "bits/stdc++.h"
- using namespace std;
- const int maxN = 1e5 + 10;
- int p[maxN],r[maxN];
- bool has[maxN];
- int __find__ (int a) {
- return p[a] = (p[a] == a ? a : __find__(p[a]));
- }
- void __union__ (int a,int b) {
- a = __find__(a);
- b = __find__(b);
- if (r[a] == r[b]) ++r[a];
- if (r[a] > r[b]) p[b] = a;
- else p[a] = b;
- }
- int main () {
- ios::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- int n, m;
- cin >> n >> m;
- for (int i = 1; i <= n; ++i) p[i] = i;
- for (int i = 1; i <= m; ++i) {
- int u, v;
- cin >> u >> v;
- __union__(u, v);
- }
- int cnt[n + 1];
- fill(cnt, cnt + n + 1, 0);
- for (int i = 1; i <= n; ++i) {
- cnt[__find__(i)]++;
- }
- int cc = 0;
- for (int i = 1; i <= n; ++i) {
- if (cnt[i] > 0) ++cc;
- }
- cout << cc << '\n';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement