Cod sursa(job #2790662)

Utilizator cristiWTCristi Tanase cristiWT Data 29 octombrie 2021 12:14:02
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
// Range minimum query.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <bits/stdc++.h>

using namespace std;

ifstream f("rmq.in");
ofstream g("rmq.out");

vector<int> v[20];
int n, m;

int Log2(int x) {
    for (int i = 31; i >= 0; i--)
        if (x & (1 << i))
            return i;
    return 0;
}

void build() {
    int N = Log2(n);
    for (int i = 1; i <= N; i++) {
        v[i].push_back(0);
        for (int j = 1; j <= n - (1 << i) + 1; j++)
            v[i].push_back(min(v[i - 1][j], v[i - 1][j + (1 << (i - 1))]));
    }
        
}

int main()
{
    f >> n >> m;
    v[0].push_back(0);
    for (int i = 1; i <= n; i++) {
        int x;
        f >> x;
        v[0].push_back(x);
    }

    build();

    while (m--) {
        int x, y;
        f >> x >> y;
        int p = Log2(y - x + 1);
        g << min(v[p][x], v[p][y - (1 << p) + 1]) << '\n';
    }
}