Cod sursa(job #2052484)

Utilizator osiaccrCristian Osiac osiaccr Data 30 octombrie 2017 17:40:40
Problema Range minimum query Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>
#include <vector>
#define DEF 100001
#define DEF2 17

using namespace std;

ifstream fin ("rmq.in");
ofstream fout ("rmq.out");

int P2[DEF2], log2[DEF], n, m;

vector < int > D[DEF];

void construct () {
    int x, y, z;
    for (int i = 1; P2[i] - 1 <= n; ++ i) {
        for (int j = 0; j <= D[i - 1].size () - P2[i - 1] - 1; ++ j) {
            x = D[i - 1][j];
            y = D[i - 1][j + P2[i - 1]];
            z = min(D[i - 1][j], D[i - 1][j + P2[i - 1]]);
            D[i].push_back (min(D[i - 1][j], D[i - 1][j + P2[i - 1]]));
        }
    }
}

int querry (int x, int y) {
    x = min (D[log2[y - x + 1]][x - 1], D[log2[y - x + 1]][y - log2[y - x + 1] - 1]);
    return x;
}

int main () {
    P2[0] = 1;
    for (int i = 1; i <= DEF2; i++) {
        P2[i] = P2[i - 1] * 2;
    }
    log2[1] = 0;
    for (int i = 2; i <= DEF; i++) {
        log2[i] = log2[i - 1];
        if (P2[log2[i] + 1] <= i)
           ++ log2[i];
    }

    fin >> n >> m;
    for (int i = 1; i <= n; ++ i) {
        int x;
        fin >> x;
        D[0].push_back (x);
    }
    construct ();
    for (; m; -- m) {
        int x, y;
        fin >> x >> y;
        fout << querry (x, y) << "\n";
    }
    return 0;
}