Pagini recente » Monitorul de evaluare | Cod sursa (job #1060307) | Cod sursa (job #1402199) | Cod sursa (job #2043657) | Cod sursa (job #1139961)
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <deque>
using namespace std;
const char infile[] = "rmq.in";
const char outfile[] = "rmq.out";
ifstream fin(infile);
ofstream fout(outfile);
const int MAXN = 100005;
const int MAXLG = 21;
const int oo = 0x3f3f3f3f;
typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;
const inline int min(const int &a, const int &b) { if( a > b ) return b; return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b; return a; }
const inline void Get_min(int &a, const int b) { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b) { if( a < b ) a = b; }
/** \RMQ
*
* RMQ[i][j] = min( A[j], A[j + 1], A[j + 2] ... A[j + (2 ^ i) - 1] )
* => RMQ[i][j] = min( RMQ[i - 1][j], RMQ[i - 1][j - 2 ^ (i - 1)]
* (j, j+1...j+2^(i - 1) - 1) (j - 2 ^ (i - 1) ... j )
*
*/
int N, M, RMQ[MAXLG][MAXN], Log[MAXN];
int A[MAXN];
inline void buildLOG() {
for(int i = 2 ; i <= N ; ++ i)
Log[i] = Log[i >> 1] + 1;
}
inline void buildRMQ() {
for(int i = 1 ; i <= N ; ++ i)
RMQ[0][i] = i;
for(int i = 1 ; (1 << i) <= N ; ++ i) {
for(int j = 1 ; j + (1 << i) - 1 <= N ; ++ j) {
int l = (1 << (i - 1));
RMQ[i][j] = RMQ[i - 1][j];
if(A[RMQ[i][j]] > A[RMQ[i - 1][j + l]])
RMQ[i][j] = RMQ[i - 1][j + l];
}
}
}
inline int Query(int x, int y) {
int lg = Log[y - x + 1];
int Ans = RMQ[lg][x];
if(A[Ans] > A[RMQ[lg][y - (1 << lg) + 1]])
Ans = RMQ[lg][y - (1 << lg) + 1];
return A[Ans];
}
int main() {
fin >> N >> M;
for(int i = 1 ; i <= N ; ++ i)
fin >> A[i];
buildLOG();
buildRMQ();
for(int i = 1 ; i <= M ; ++ i) {
int x, y;
fin >> x >> y;
fout << Query(x, y) << '\n';
}
fin.close();
fout.close();
return 0;
}