Cod sursa(job #3225720)

Utilizator DistroZLeonStinga Alexandru DistroZLeon Data 18 aprilie 2024 16:25:32
Problema Range minimum query Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <iostream>
#include <fstream>
using namespace std;

const int NMAX = 1e5;
int a[NMAX + 1];
int rmq[NMAX + 1][18], LOG[NMAX + 1];

int query2(int x, int y) {
    int diff = y - x + 1;
    int st = x;
    int sol = 1e9;
    for(int i = 0; (1 << i) <= diff; i++) {
        if((1 << i) & diff) {
            sol = min(sol, rmq[st][i]);
            st += (1 << i);
        }
    }
    return sol;
}

int main() {
    int n,m;
    ifstream fin("rmq.in");
    ofstream fout("rmq.out");
    fin >> n>>m;
    for(int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    for(int i = 2; i <= n; i++) {
        LOG[i] = LOG[i / 2] + 1;
    }
    for(int i = 1; i <= n; i++) {
        rmq[i][0] = a[i];
    }
    for(int j = 1; (1 << j) <= n; j++) {
        for(int i = 1; i + (1 << j) - 1 <= n; i++) {
            rmq[i][j] = min(rmq[i][j - 1], rmq[i + (1 << (j - 1))][j - 1]);
        }
    }
    int x,y;
    for(int i=0;i<m;++i){
        fin>>x>>y;
        fout<<query2(x,y);
    }
    return 0;
}