Advertisement
cosenza987

Untitled

Apr 20th, 2022
1,262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. // Problem: A. DSU with rollback
  2. // Contest: Codeforces - ITMO Academy: pilot course - Disjoint Sets Union - Step 3
  3. // Memory Limit: 256 MB
  4. // Time Limit: 2000 ms
  5. // Date / Time: 2022-04-20 22:42:16
  6. // Author: cosenza
  7. // всё что ни делается - всё к лучшему
  8. // check list -> long long, special cases, array size, mod (a*b%p*c%p not a*b*c%p  ,  (a-b+p)%p not a-b )
  9. //
  10. // Powered by CP Editor (https://cpeditor.org)
  11.  
  12. //Слава Україні, Героям слава 🇺🇦
  13.  
  14. #include <bits/stdc++.h>
  15.  
  16. using namespace std;
  17.  
  18. const int N = 2e5 + 7;
  19.  
  20. int par[N], cnt;
  21.  
  22. vector<vector<int>> v;
  23. vector<int> tmp;
  24.  
  25. int find(int a) {
  26.     return par[a] == a ? a : find(par[a]);
  27. }
  28.  
  29. void unite(int u, int v) {
  30.     if((u = find(u)) == (v = find(v))) {
  31.         return;
  32.     }
  33.     par[u] = v;
  34.     cnt--;
  35.     tmp.push_back(u);
  36. }
  37.  
  38. int main() {
  39.     ios_base::sync_with_stdio(false);
  40.     cin.tie(0);
  41.     for(int i = 0; i < N; i++) {
  42.         par[i] = i;
  43.     }
  44.     int n, q;
  45.     cin >> n >> q;
  46.     cnt = n;
  47.     string s;
  48.     while(q--) {
  49.         cin >> s;
  50.         if(s == "union") {
  51.             int u, v;
  52.             cin >> u >> v;
  53.             unite(u, v);
  54.             cout << cnt << "\n";
  55.         } else if(s == "persist") {
  56.             v.push_back(tmp);
  57.             tmp.clear();
  58.         } else {
  59.             for(auto e : tmp) {
  60.                 par[e] = e;
  61.                 cnt++;
  62.             }
  63.             tmp = v.back();
  64.             v.pop_back();
  65.             cout << cnt << "\n";
  66.         }
  67.     }
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement