fork download
  1. //NiceDuck
  2. #include "bits/stdc++.h"
  3. typedef long long ll;
  4. using namespace std;
  5. #define FILE "000"
  6. #define foru(i,a,b) for(int i=(int)(a); i<=(int)(b); ++i)
  7. #define ford(i,a,b) for(int i=(int)(a); i>=(int)(b); --i)
  8. #define fastio ios_base::sync_with_stdio(0);cin.tie(0);
  9. #define pb push_back
  10. #define fi first
  11. #define se second
  12. #define el "\n"
  13. #define MASK(i) (1LL<<(i))
  14. #define BIT(i,j) (((i)>>(j))&1)
  15. #define TIME 1.0*clock()/CLOCKS_PER_SEC
  16. #define LOG 20
  17.  
  18. const ll MAX=2e5+5;
  19. int n,q,cnt;
  20. struct Dsu
  21. {
  22. vector<pair<int,int> > history;
  23. int par[MAX],sz[MAX];
  24. void init()
  25. {
  26. foru(i,1,n)
  27. {
  28. par[i]=i;
  29. sz[i]=1;
  30. }
  31. }
  32. int find_par(int x)
  33. {
  34. while(x!=par[x]) x=par[x];
  35. return x;
  36. }
  37. int join(int u, int v)
  38. {
  39. u=find_par(u); v=find_par(v);
  40. if(u==v)
  41. {
  42. history.pb({-1,-1});
  43. return 0;
  44. }
  45. if(sz[u]<sz[v]) swap(u,v);
  46. history.pb({v,sz[u]});
  47. sz[u]+=sz[v];
  48. par[v]=u;
  49. return -1;
  50. }
  51. int rollback(int ver)
  52. {
  53. int res=0;
  54. while((int)history.size()>ver)
  55. {
  56. pair<int,int> pa=history.back();
  57. history.pop_back();
  58. if(pa.fi==-1) continue;
  59. int v=pa.fi, old=pa.se;
  60. int u=par[v];
  61. sz[u]=old;
  62. par[v]=v;
  63. ++res;
  64. }
  65. return res;
  66. }
  67. } dsu;
  68.  
  69. int main()
  70. {
  71. fastio
  72. if(fopen(FILE ".inp","r"))
  73. {
  74. freopen(FILE ".inp","r",stdin); freopen(FILE ".out","w",stdout);
  75. }
  76. cin>>n>>q;
  77. cnt=n;
  78. dsu.init();
  79. cin.ignore();
  80. vector<int> v;
  81. v.clear();
  82. while(q--)
  83. {
  84. string str; cin>>str;
  85. if(str=="persist") v.pb(dsu.history.size());
  86. else if(str=="union")
  87. {
  88. int u,v; cin>>u>>v;
  89. cnt+=dsu.join(u,v);
  90. cout<<cnt<<el;
  91. }
  92. else
  93. {
  94. int x=v.back();
  95. cnt+=dsu.rollback(x);
  96. cout<<cnt<<el;
  97. v.pop_back();
  98. }
  99. }
  100. return 0;
  101. }
  102.  
Success #stdin #stdout 0.01s 5324KB
stdin
Standard input is empty
stdout
Standard output is empty