Cod sursa(job #2031320)

Utilizator Horia14Horia Banciu Horia14 Data 2 octombrie 2017 23:42:38
Problema Range minimum query Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include<fstream>
#define MAX_N 100000
#define MAX_LOG 17
using namespace std;

int v[MAX_N], sparse[MAX_N][MAX_LOG], n, m;

inline int log2(int x) {
    return 31 - __builtin_clz(x);
}

inline int RMQ(int low, int high) {
    int l, k;
    l = high - low + 1;
    k = log2(l);
    return min(v[sparse[low][k]],v[sparse[low + l - (1 << k)][k]]);
}

int main() {
    int i, j, x, y;
    ifstream fin("rmq.in");
    ofstream fout("rmq.out");
    fin >> n >> m;
    for(i=0; i<n; i++) {
        fin >> v[i];
        sparse[i][0] = i;
    }
    for(j=1; (1 << j) <= n; j++)
        for(i=0; i + (1 << j) - 1 <n; i++)
            if(v[sparse[i][j-1]] < v[sparse[i + (1 << (j-1))][j-1]])
                sparse[i][j] = sparse[i][j-1];
            else sparse[i][j] = sparse[i + (1 << (j-1))][j-1];

    for(i=1; i<=m; i++) {
        fin >> x >> y;
        fout << RMQ(x-1,y-1) << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}