0

I have a splay tree for which I have implemented range_sum(left,right) which adds all the elements in the tree in range from left to right and it works in logarithmic time, is there anyway I can make a function range_up(left,right ,delta) which adds delta to every element in the range from left to right and works in logarithmic time?

aelc
  • 13
  • 5
  • That might make the tree no longer a valid BST. Can you give some examples of what you’re referring to here? – templatetypedef Aug 02 '21 at 14:15
  • Well basically it's a splay tree so make use of the fact that it's not static so I don't traverse over it instead i splay the node and long story short this runs in logarithmic time, now I want a function so that it will add delta to every element in the given range which is left and right. – aelc Aug 02 '21 at 17:12
  • Does your tree store key/value pairs, and you're adding to the values? Or does the tree just store keys, and you're actually changing the keys? – templatetypedef Aug 02 '21 at 17:37
  • it stores key,value and I am adding values – aelc Aug 02 '21 at 19:56

1 Answers1

0

You can do this using lazy updates. The idea is to put in each node a field into each node that says “this node, and all nodes below it, implicitly have Δ added to all their values.” When performing a rotation in your splay logic, you can then push this delta value down.

To add an amount to all values in a range, start off by doing a search for the lowest common ancestor of the nodes in the range (this is the node where one end of the range is in one direction and the other is in the other). Update the delta field there, which adds delta to all the nodes in that subtree. This includes all the nodes you want, plus some you don’t. From there, do a pair of predecessor/successor searches for the min/max elements of the range. As you do those searches, which will walk you down from the LCA to two leaves, update the delta fields of the nodes you encounter outside of the range to undo the delta you added in at the LCA. (More precisely, as you walk down, every time you step out of the range add -Δ at the node to undo the application of the delta, and when you step back in the range add Δ to the node to correct for it.)

This does two root-to-leaf walks, and provided you splay both at the end the amortized cost of the update is O(log n).

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065