Advertisement
maycod23

Untitled

May 30th, 2022
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. class segtree
  2. {
  3. public:
  4. vl seg;
  5. segtree(ll n)
  6. {
  7. seg = vl (4 * n + 2);
  8. }
  9. void build(ll ind, ll low, ll high, vl & v)
  10. {
  11. //build (ind,low,high)-->curr ind->ind of seg with range [low,high] for that
  12. //1.>write base case whether this range is leaf node or not if that then seg[ind]=a[low];
  13. //2.>build for the left child and build for the right child also
  14. //3.>calculate the work for (low,high) for curr ind
  15.  
  16.  
  17. // build-> work for[low,high] precomputed already
  18. // >base case->work for left and right childs-> work for curr ind
  19. if (low == high)
  20. {
  21. seg[ind] = v[low]; return;
  22. }
  23.  
  24. ll mid = low + (high - low) / 2;
  25. build(2 * ind, low, mid, v);
  26. build((2 * ind) + 1, mid + 1, high, v);
  27.  
  28. seg[ind] = seg[2 * ind] + seg[(2 * ind) + 1];
  29. }
  30.  
  31. // work[l, r] precomputed and stored
  32. // query[l, r]->work[l, r] using some cases
  33. // update(i, val)-> reach that range of seg and update there l = along with that kee upddaing fpr each parent also
  34. ll query(ll ind, ll low, ll high, ll l, ll r, vl & v)
  35. {
  36. //1.>no overlap with current ind, retur no work---[low,high][l,r]\\[l,r][low,high]
  37. if (high < l || r < low) return 0;//no work
  38.  
  39. //2.>complete overlap-->-[l---low,high,---r]
  40. if (l <= low && high <= r)
  41. {
  42. return seg[ind];
  43. }
  44.  
  45. //3.>partial overlap--->[low---l,r---high]
  46. ll mid = low + (high - low) / 2;
  47. ll left = query(2 * ind, low, mid, l, r, v);
  48. ll right = query((2 * ind) + 1, mid + 1, high, l, r, v);
  49. return (left + right);
  50. // t.c->O(k*logN)// worst cases me kuch se hi base pe jayega
  51. }
  52.  
  53. void update(ll ind, ll low, ll high, ll i, ll val, vl & v)
  54. {
  55. //1.>base case when you reach the leaf node
  56. if (low == high)
  57. {
  58. seg[ind] = val; return;
  59. }
  60.  
  61. //2.>call for either left and right
  62. ll mid = low + (high - low) / 2;
  63. if (i <= mid) update(2 * ind, low, mid, i, val, v);
  64. else update((2 * ind) + 1, mid + 1, high, i, val, v);
  65.  
  66.  
  67. //3.>update this curr node also
  68. seg[ind] = seg[2 * ind] + seg[(2 * ind) + 1];
  69. }
  70. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement