Блог пользователя rr459595

Автор rr459595, история, 7 лет назад, По-английски

Link to the problem :- http://www.spoj.com/problems/TEMPLEQ/

In this question for answering type 3 queries where we have to update the nodes with value greater than x, we create a segment tree and do lazy propagation. In segment tree, internal nodes are maximum of left and right child.

For answering type 1 queries (updating), I need the last index of a particular element. If array is 1 2 2 2 2 5, last index of 2 is 5.

My question is how can I find the last index of a particular element using binary search in the above segment tree (where internal nodes have max of left and right child) in O(logn) time instead of O(log2n)?

Thanks.

  • Проголосовать: нравится
  • +10
  • Проголосовать: не нравится

»
7 лет назад, # |
Rev. 2   Проголосовать: нравится +5 Проголосовать: не нравится

You don't need to perform an additional binary search. If you have the correct information in the nodes, one query on the tree is enough.

You need to keep, not maximum of left and right children on each node, but first and last element of this node. You know the tree is sorted and you have first and last element for every node, so say you're looking for the last occurrence of element x: if first element of right child is  ≤ x, then go to right child, otherwise go to left child. Keep doing that until you reach a leaf. That's the index you're looking for.

Note: Last element is also needed, for the case when you need to find the first occurrence of an element.

  • »
    »
    7 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    This basically is binary search, but yes, an implicit one, not explicit. Thumbs up

  • »
    »
    7 лет назад, # ^ |
    Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

    So silly of me :( . I actually had max of internal children stored in the node for updating nodes based on threshold. I will add one more field to the node now to perform binary search. Thanks !