Cod sursa(job #1116563)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 22 februarie 2014 17:56:43
Problema Range minimum query Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.31 kb
#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 MAXL = 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; }

template<class T, const int MAXN, const int MAXLG, const int A[]>
class RMQ {
    //static const int MAXN = 1005;
    //static const int MAXLG = 21;
    T rmq[MAXLG][MAXN];
    T Log[MAXN];
public:
    //RMQ(const int &N) {
    //    BuildLog(N);
    //    BuildRMQ(N);
    //}
    inline void BuildLog(const int &N) {
        for(int i = 2 ; i <= N ; ++ i)
            Log[i] = Log[i >> 1] + 1;
    }
    inline void BuildRMQ(const int &N) {
        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) {
                rmq[i][j] = rmq[i - 1][j];
                int l = (1 << (i - 1));
                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 N, A[MAXN], M;
RMQ <int, MAXN, MAXL, A> r;

int main() {
    fin >> N >> M;
    for(int i = 1 ; i <= N ; ++ i)
        fin >> A[i];
    r.BuildLog(N);
    r.BuildRMQ(N);
    for(int i = 1 ; i <= M ; ++ i) {
        int x, y;
        fin >> x >> y;
        fout << r.Query(x, y) << '\n';
    }
    fin.close();
    fout.close();
    return 0;
}