-1

I am learning segment trees (on the example of range minimum query) and have some problem understanding the reason behind the part of the algorithm for querying a segment tree.

I have no problem understanding the part of construction the segment tree, I can not understand why in this function:

int RMQUtil(int *st, int ss, int se, int qs, int qe, int index)
{
    // If segment of this node is a part of given range, then return the min of the segment
    if (qs <= ss && qe >= se)
        return st[index];    // this is the part I am struggling with

    // If segment of this node is outside the given range
    if (se < qs || ss > qe)
        return INT_MAX;

    // If a part of this segment overlaps with the given range
    int mid = getMid(ss, se);
    return minVal(RMQUtil(st, ss, mid, qs, qe, 2*index+1), RMQUtil(st, mid+1, se, qs, qe, 2*index+2));
}

If segment of this node is a part of given range, then return the min of the segment.

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • If the segment is a part of the given range, then the min of the segment is a candidate for the final answer. – justmscs Jan 18 '15 at 06:48

2 Answers2

0

If segment of this node is a part of given range, then you already know the answer for the subsegment [ss, se] (it is st[index]) and you have no need to go deeper.

Ivan Smirnov
  • 4,365
  • 19
  • 30
0

in the query, you want to find the minimum number in the range of [qs,qe].

now, this in terms of segment trees can be expressed as first finding the middle of the interval i.e mid=(qs+qe)/2

and the logic is that the minimum in the range [qs,qe] is equal to the minimum of finding the minimum in range [qs,mid] and [mid+1,qe].

This is written in ur code in the following lines:

int mid = getMid(ss, se);
    return minVal(RMQUtil(st, ss, mid, qs, qe, 2*index+1), RMQUtil(st, mid+1, se, qs, qe, 2*index+2));
nikhil jain
  • 105
  • 9