Cod sursa(job #2146427)

Utilizator andreigeorge08Sandu Ciorba andreigeorge08 Data 27 februarie 2018 23:22:20
Problema Range minimum query Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#include <bits/stdc++.h>

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

long long rmq[22][100005], n, q;
int p[100005];

void Build()
{
    p[1] = 0;
    for(int i = 2; i <= n; i++)
        p[i] = p[i / 2] + 1;

    int L = p[n];

    for(int i = 1; i <= L; i++)
        for(int j = 1; j <= n - (1 << i) + 1; j++)
            rmq[i][j] = min(rmq[i - 1][j],
                            rmq[i - 1][j + (1 << (i - 1))]);
}
void Citire()
{
    int x, y;
    fin >> n >> q;
    for(int i = 1; i <= n; i++)
        fin >> rmq[0][i];

    Build();

    while(q--)
    {
        fin >> x >> y;
        if(x > y) swap(x, y);

        int L = p[y - x + 1];
        int t = rmq[L][x];
        int t1 = rmq[L][y - (1 << L) + 1];

        fout << min(t, t1) << "\n";
    }
}
int main()
{
    Citire();
    return 0;
}