Search code examples
cdata-structuressegment-tree

Query code unexpectedly modifies array instead of returning the index


In this tutorial, why does the query() function modify the content of M in the last 4 lines of code, instead of just returning the node index?

I think there's a problem with his approach: the modified M array won't be able to handle future RMQ [range minimum Queries], since m[node] stores the index of a recent query.

Here's the code I'm talking about:

int query(int node, int b, int e, int M[MAXIND], int A[MAXN], int i, int j)
{
    int p1, p2;

    // if the current interval doesn't intersect 
    // the query interval return -1
    if (i > e || j < b)
        return -1;

    // if the current interval is included in 
    // the query interval return M[node]
    if (b >= i && e <= j)
        return M[node];

    // compute the minimum position in the 
    // left and right part of the interval
    p1 = query(2 * node, b, (b + e) / 2, M, A, i, j);
    p2 = query(2 * node + 1, (b + e) / 2 + 1, e, M, A, i, j);

    // return the position where the overall 
    // minimum is
    if (p1 == -1)
        return M[node] = p2;
    if (p2 == -1)
        return M[node] = p1;
    if (A[p1] <= A[p2])
        return M[node] = p1;
    return M[node] = p2;
}

Solution

  • It is definitely a bug. You're right, it should just return an index without updating the array.