如何使用段树查找数组中的前2个最小整数

时间:2019-02-17 18:42:01

标签: c++ algorithm segment-tree

如何找到要查询和更新查询的前两个最小要素。

我认为我必须使用细分(segment-tree)

2 个答案:

答案 0 :(得分:0)

<algorithm>中,您似乎正在寻找std::nth_element。这将确保正确放置在所需位置的元素(第二个元素),但还应确保元素少于该元素(在本例中为第一个元素)位于其左侧。所有其他元素在您想要的位置的右​​侧保持不确定的顺序。下面的程序:

#include <algorithm>
#include <iostream>
#include <iterator>

int main() {
    using std::begin;
    using std::end;
    using std::next;

    int array[] = {5, 2, 1, 4, 3};

    std::copy(begin(array), end(array), std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';

    std::nth_element(begin(array), next(begin(array)), end(array));

    std::copy(begin(array), end(array), std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
}

将输出(在我的机器上):

5 2 1 4 3 
1 2 5 4 3 

答案 1 :(得分:0)

这可以通过对RMQ段树进行简单修改来解决

这里的O(N log N)方法:

  1. 为给定数组构建细分树
  2. 对于分段树中的每个节点,存储当前范围及其索引的最小值
  3. 按以下方式处理类型1的查询:
    • 查找范围[L,R]及其索引中的最小值
    • 在[L,found_index-1]和[found_index + 1,R]范围内找到最小值
  4. 对于类型2的查询,只需更新细分树