-4

How to find the first two minimum elements to asking a query and updating it.

In my opinion, I must use segmentry (segment-tree)

kalimba
  • 408
  • 4
  • 14
J. Doe
  • 1
  • 4

2 Answers2

0

From <algorithm> it seems you are looking for std::nth_element. It will make sure that the elements at the desired position, the second element, is correctly placed but also make sure that elements less that it, in this case, the first element, is to the left of it. All other elements remain in an unspecified order to the right of the position you wanted. The program below:

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

will output (on my machine):

5 2 1 4 3 
1 2 5 4 3 
Bo R
  • 2,334
  • 1
  • 9
  • 17
0

This can be solved with simple modification to RMQ segment tree

Here`s O(N log N) approach:

  1. Build the segment tree for given array
  2. For each node in segment tree store minimum value for current range and its index
  3. Process queries of type 1 as follows:
    • Find minimum value in range [L,R] and its index
    • Find minimum value in ranges [L, found_index-1] and [found_index+1, R]
  4. For queries of type 2 just update the segment tree
Photon
  • 2,717
  • 1
  • 18
  • 22