How to find the first two minimum elements to asking a query and updating it.
In my opinion, I must use segmentry (segment-tree)
How to find the first two minimum elements to asking a query and updating it.
In my opinion, I must use segmentry (segment-tree)
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
This can be solved with simple modification to RMQ segment tree
Here`s O(N log N) approach: