Advertisement
arujbansal

harmony

Jan 22nd, 2021
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. void dbg_out() { cerr << endl; }
  6. template<typename Head, typename... Tail>
  7. void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); }
  8. #define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
  9.  
  10. #define rng_init mt19937 rng(chrono::steady_clock::now().time_since_epoch().count())
  11. #define all(x) (x).begin(), (x).end()
  12. #define sz(x) (int) (x).size()
  13. // #define int long long
  14.  
  15. const int MXN = 2e5 + 5, INF = 1e9 + 5;
  16. int par[MXN], compSz[MXN];
  17.  
  18. int get(int x) {
  19.     if (par[x] == x) return x;
  20.     return par[x] = get(par[x]);
  21. }
  22.  
  23. bool unite(int x, int y) {
  24.     x = get(x), y = get(y);
  25.     if (x == y) return false;
  26.  
  27.     if (compSz[y] > compSz[x]) swap(x, y);
  28.     compSz[x] += compSz[y];
  29.     par[y] = x;
  30.  
  31.     return true;
  32. }
  33.  
  34. void solve() {
  35.     int N, M;
  36.     cin >> N >> M;
  37.  
  38.     for (int i = 0; i <= N + 1; i++) {
  39.         par[i] = i;
  40.         compSz[i] = 1;
  41.     }
  42.  
  43.     int ans = 0;
  44.  
  45.     vector<int> diff(N + 2, 0);
  46.     vector<pair<int, int>> edges;
  47.  
  48.     for (int i = 0; i < M; i++) {
  49.         int u, v;
  50.         cin >> u >> v;
  51.         if (u > v) swap(u, v);
  52.  
  53.         unite(u, v);
  54.  
  55.         edges.emplace_back(u, v);
  56.  
  57.         diff[u + 1]++;
  58.         diff[v]--;
  59.     }
  60.  
  61.     for (const auto &[u, v] : edges) {
  62.         ans += unite(u, u + 1) + unite(v, v - 1);
  63.     }
  64.  
  65.     for (int i = 1; i <= N; i++)
  66.         diff[i] += diff[i - 1];
  67.  
  68.     for (int i = 1; i <= N; i++) {
  69. //        dbg(i, diff[i]);
  70.         if (diff[i] <= 0) continue;
  71.  
  72.         if (diff[i - 1] > 0) ans += unite(i - 1, i);
  73.         if (diff[i + 1] > 0) ans += unite(i, i + 1);
  74.     }
  75.  
  76.     cout << ans;
  77. }
  78.  
  79. signed main() {
  80.     ios_base::sync_with_stdio(false);
  81.     cin.tie(nullptr);
  82.  
  83. #ifdef local
  84.     freopen("input.txt", "r", stdin);
  85.     freopen("output.txt", "w", stdout);
  86. #endif
  87.  
  88.     int TC = 1;
  89.     // cin >> TC;
  90.     while (TC--) solve();
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement