【问题标题】:Query code unexpectedly modifies array instead of returning the index查询代码意外修改数组而不是返回索引
【发布时间】:2015-01-03 01:53:42
【问题描述】:

this tutorial中,为什么query()函数在最后4行代码中修改M的内容,而不是只返回节点索引?

我认为他的方法存在问题:修改后的 M 数组将无法处理未来的 RMQ [范围最小查询],因为m[node] 存储了最近查询的索引。

这是我正在谈论的代码:

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;
}

【问题讨论】:

    标签: c data-structures segment-tree


    【解决方案1】:

    这绝对是一个错误。没错,它应该只返回一个索引而不更新数组。

    【讨论】:

    • 很多人都参考了该教程,因此突出显示该错误并可能纠正它变得很重要..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 2016-03-24
    • 2021-06-22
    • 2013-12-01
    • 2021-05-23
    • 2018-11-12
    相关资源
    最近更新 更多