Korotkodul

Better Sparse Table

Nov 25th, 2021 (edited)
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <vector>
  4. #include <set>
  5. #include <string>
  6. #include <algorithm>
  7. using namespace std;
  8. using ll = long long;
  9. using unt = unsigned int;
  10. void cv(vector <unt> v){
  11. for (auto x: v) cout<<x<<' ';
  12. cout<<'\n';
  13. }
  14.  
  15. vector <unt> ar(1);
  16.  
  17. vector <pair<unt,unt>> qr(1);
  18.  
  19. unt sm;
  20.  
  21. vector <vector <unt> > wrk;
  22.  
  23. vector <unt> power;
  24.  
  25. void make(){
  26. int lvl = 1,l,r;
  27. //cout<<"sz= "<<ar.size()<<'\n';
  28. while (pow(2,lvl) <= ar.size()){
  29. //cout<<"lvl = "<<lvl<<'\n';
  30. vector <unt> last = wrk[wrk.size() - 1];
  31. int len = pow(2, lvl);
  32. int hlf = len / 2;
  33. for (int i = 0; i<=ar.size()-len; ++i){
  34. // cout<<"i = "<<i<<'\n';
  35. l = i;
  36. r = i + len - 1;
  37. unt L = last[l];
  38. unt R = last[l+hlf];
  39. sm = min(L, R);
  40. power.push_back(sm);
  41. }
  42. wrk.push_back(power);
  43. power.clear();
  44. lvl++;
  45. }
  46. }
  47. int main()
  48. {
  49. ios::sync_with_stdio(0);
  50. cin.tie(0);
  51. cout.tie(0);
  52. unt N,M,A,B;
  53. while (true){
  54. cin>>N>>M>>A>>B;
  55. if (N==0 && M==0 && A==0 && B==0) break;
  56. ar.clear();
  57. qr.clear();
  58. unt d;
  59. unt d1, d2;
  60. for (int i = 1;i<=N+M*2;++i){
  61. if (i <= N){
  62. d = A * i + B;
  63. ar.push_back(d);
  64. }
  65. else{
  66. d1 = (A * i + B);
  67. d1 %= N;
  68. d1++;
  69. i++;
  70. d2 = (A * i + B);
  71. d2 %= N;
  72. d2++;
  73. //cout<<"d1d2= "<<d1<<' '<<d2<<'\n';
  74. qr.push_back({d1, d2});
  75. }
  76. }
  77. for (int i = 0; i < ar.size();++i){
  78. sm = ar[i];
  79. power.push_back(sm);
  80. }
  81. wrk.push_back(power);
  82. power.clear();
  83. make();
  84. ll ans;
  85. ll tot = 0;
  86. /*cout<<"qr:\n";
  87. for (auto x: qr) cout<<x.first<<' '<<x.second<<'\n';
  88. cout<<'\n';*/
  89. for (auto Q: qr){
  90. unt a = min(Q.first, Q.second);
  91. unt b = max(Q.first, Q.second);
  92. a--;
  93. b--;
  94. //cv(ar);
  95. //cout<<"ab= "<<a<<' '<<b<<'\n';
  96. unt LVL = floor(log(b-a+1) / log(2));
  97. vector <unt> now = wrk[LVL];
  98. ll lft = now[a];
  99. ll rgt = now[b - pow(2,LVL) + 1];
  100. ans = min(lft, rgt);
  101. //cout<<"ans= "<<ans<<'\n';
  102. tot += ans;
  103. }
  104. cout<<tot<<"\n";
  105. wrk.clear();
  106. }
  107.  
  108. }
Add Comment
Please, Sign In to add comment