Advertisement
newb_ie

dsu

Dec 25th, 2021
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. #include "bits/stdc++.h"
  2.  
  3. using namespace std;
  4.  
  5. const int maxN = 1e5 + 10;
  6. int p[maxN],r[maxN];
  7. bool has[maxN];
  8.  
  9. int __find__ (int a) {
  10. return p[a] = (p[a] == a ? a : __find__(p[a]));
  11. }
  12.  
  13. void __union__ (int a,int b) {
  14. a = __find__(a);
  15. b = __find__(b);
  16. if (r[a] == r[b]) ++r[a];
  17. if (r[a] > r[b]) p[b] = a;
  18. else p[a] = b;
  19. }
  20.  
  21. int main () {
  22. ios::sync_with_stdio(false);
  23. cin.tie(nullptr);
  24. cout.tie(nullptr);
  25. int n, m;
  26. cin >> n >> m;
  27. for (int i = 1; i <= n; ++i) p[i] = i;
  28. for (int i = 1; i <= m; ++i) {
  29. int u, v;
  30. cin >> u >> v;
  31. __union__(u, v);
  32. }
  33. int cnt[n + 1];
  34. fill(cnt, cnt + n + 1, 0);
  35. for (int i = 1; i <= n; ++i) {
  36. cnt[__find__(i)]++;
  37. }
  38. int cc = 0;
  39. for (int i = 1; i <= n; ++i) {
  40. if (cnt[i] > 0) ++cc;
  41. }
  42. cout << cc << '\n';
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement