Pagini recente » Cod sursa (job #2128331) | Cod sursa (job #1790881) | Cod sursa (job #486296) | Cod sursa (job #2248764) | Cod sursa (job #2197864)
#include <bits/stdc++.h>
using namespace std;
template <typename ForwardIterator, typename Function>
class RMQ{
public:
ForwardIterator first, last;
using T = typename iterator_traits<ForwardIterator>::value_type;
vector<T> V; //value
vector<vector<T> > M; //index of the largest/smallest value
Function func;
vector<int> L; //logs
int n = 0;
RMQ(ForwardIterator a, ForwardIterator b, Function f) : first(a), last(b), func(f) {};
void build(){
while(first!=last){
V.emplace_back(*first);
first++;
n++;
}
M.resize(n);
for(int i = 0; i < n; i++)
M[i].emplace_back(i);
L.emplace_back(0);
L.emplace_back(0);
for(int i = 2; i <= n; i++)
L.emplace_back(L[i/2] + 1);
for(int step = 1; step <= L[n]; step++){
for(int i = 0; i < n - (1<<step) + 1; i++)
M[i].emplace_back(func(V[ M[i][step - 1] ], V[ M[i + (1<<(step - 1))][step - 1] ]) ?
M[i][step - 1] : M[i + (1<<(step - 1))][step - 1]);
}
}
int iQuery(int begin, int end){
int step = L[end - begin + 1];
if(func(V[ M[begin][step] ], V[ M[end - (1<<step) + 1][step] ] ))
return M[begin][step];
return M[end - (1<<step) + 1][step];
}
T vQuery(int begin, int end){
return V[iQuery(begin, end)];
}
};
int n, m;
vector<int> V;
RMQ<vector<int>::iterator, function<bool(int, int)> > *R;
void Read()
{
scanf("%d %d", &n, &m);
int x;
for(int i = 0; i < n; i++) {
scanf("%d", &x);
V.emplace_back(x);
}
}
void Solve()
{
int a, b;
//clock_t t = clock();
R->build();
//t = clock() - t;
//cerr<<(double)t/CLOCKS_PER_SEC<<"\n";
for(int i = 0; i < m; i++){
scanf("%d %d", &a, &b);
printf("%d\n", R->vQuery(a - 1, b - 1) );
}
}
int main()
{
//ios_base::sync_with_stdio(false);
freopen("rmq.in", "r", stdin);
freopen("rmq.out", "w", stdout);
//clock_t t = clock();
Read();
R = new RMQ<vector<int>::iterator, function<bool(int, int)> >
(V.begin(), V.end(), [](int a, int b) -> bool { return a < b; });
Solve();
//t = clock() - t;
//cerr<<(double)t/CLOCKS_PER_SEC<<"\n";
delete R;
return 0;
}