Cod sursa(job #1409753)

Utilizator valiro21Valentin Rosca valiro21 Data 30 martie 2015 18:17:00
Problema Range minimum query Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <fstream>
#include <vector>

using namespace std;

vector<int> v;
vector<vector<int> > a;
int x, y, n, q, r;

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

    fin >> n >> q;
    v.push_back (0);
    a.push_back (*new vector<int> ());
    for (int i = 1; i <= n; i++)
        fin >> x,
        v.push_back (x),
        a.push_back (*new vector<int>()),
        a[i].push_back (i);

    for (int i = 1, pw = 2; pw <= n; i++, pw<<=1)
        for (int j = 1; j <= n - pw + 1; j++)
            a[j].push_back ( (v[a[j][i-1]] < v[a[j+(pw>>1)][i-1]]) ? a[j][i-1] : a[j+(pw>>1)][i-1] );

    for (int i = 1; i <= q; i++) {
        fin >> x >> y;
        r = v[x];

        int j = 0, nr = y-x+1;
        while (nr) {
            if (nr&1) {
                r = min (r, v[a[x][j]]);
                x += 1<<j;
            }
            j++;
            nr >>= 1;
        }

        fout << r << '\n';
    }

    return 0;
}