我正在解决的问题的一部分涉及在数组(RMQ)的范围内获得最小值,所以我实现了一个段树,到目前为止它工作正常。然后我想更新原始数组中的一项(没有超过一项的更新)并在段树中更新它。到目前为止,我所做的是从上到下遍历线段树,直到到达叶子,但这似乎有一些错误。这是代码的更新部分,那里似乎有什么问题?
PS n 不是 2 的倍数(我不知道这是否会影响解决方案)
public void update(int i, int k) {
update(i, k, 0, 0, n - 1);
}
/// <summary>
/// update one item in the segment tree
/// </summary>
/// <param name="i">The index of the element to be updated in the original array</param>
/// <param name="k">The new value</param>
/// <param name="j">The current index in the segment tree</param>
/// <param name="from">range start index (inclusive)</param>
/// <param name="to">range end index (inclusive)</param>
private void update(int i, int k, int j, int from, int to) {
tree[j] = Math.Min(tree[j], k);
if (from == to) return;
int mid = from + (to - from) / 2;
if (from <= i && mid >= i) {
update(i, k, 2 * j + 1, from, mid);
} else {
update(i, k, 2 * j + 2, mid + 1, to);
}
}
PS问题的其他部分可能有一些bug,但似乎这是最有可能出现bug的部分。