1

I have a vector of objects T and I want to find a minimum in a given range. I implemented segment tree for an efficient searching. What is the efficient way to update the tree if I know that I will alternate push_back, pop_back and query.

Is it necessary to recalculate segment tree after each push_back and pop_back ? I would like to get near to O ( log n ). The tree construction was inspired by this https://www.geeksforgeeks.org/iterative-segment-tree-range-minimum-query/. Thank you.

Simplified:

...
std::vector <int> vec { 10, 35, 30, 12, 5, -5, 70 };
constructTree ( vec );

std::cout << minQuery (5, 6 ); // min is -5
vec.push_back ( -8 );

// Is there better way to update the tree without construct whole tree again after push/pop _back ?
constructTree ( vec ); 

std::cout << minQuery (6, 7 ); // min is -8
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

construct tree with power of 2 nodes, then only reconstruct tree with double amount of nodes if needed - it's possible to make amortized cost of rebuild close to log(n) or you can just create a very large tree if memory is not an issue

for all extra nodes store value of Infinity

then push_back is just changing one node value - which is a classic thing in segment trees can be done in O(log n)

pop_back is similar - just changing last non-infinity node value to Infinity

Photon
  • 2,717
  • 1
  • 18
  • 22