Cod sursa(job #2754408)

Utilizator andreiiorgulescuandrei iorgulescu andreiiorgulescu Data 25 mai 2021 18:58:38
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.38 kb
#include <bits/stdc++.h>

using namespace std;

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

int n,m,v[100005],ln[100005],r[20][100005];

/*
int query(int st,int dr,int a,int b,int p)
{
    int fs = 2 * p,fd = 2 * p + 1,mij = (a + b) / 2;
    if (st <= a and dr >= b)
        return arbint[p];
    if (st <= mij and dr <= mij)
        return query(st,dr,a,mij,fs);
    else if (st > mij and dr > mij)
        return query(st,dr,mij + 1,b,fd);
    else
        return min(query(st,dr,a,mij,fs),query(st,dr,mij + 1,b,fd));
}
*/


///r[i][j] = min (v[j], v[j-1], ..., v[j - 2^i + 1]) = minimul pe intervalul de lungime 2^i care se termina in j

/// r[i][j] = min(r[i - 1][j], r[i - 1][j - 2^(i - 1)]

/// QUERY(a,b)
//l = [log(b-a)] (Lungimea intervalului)
//lg[1] = 0;
//for (i = 1; i <= n; i++)
//{
//    lg[i] = 1 + lg[i/2];
//}

/// min( r[l][a + (2^l) - 1],r[l][b])


/// r[0][j] = v[j]


int query(int x,int y)
{
    int l = ln[y - x];
    return min(r[l][x + (1 << l) - 1],r[l][y]);
}

int main()
{
    /*
    int i,x,y,a,b,p,fs,fd;
    bool boo = true;
    in >> n >> m;
    for (i = 1; i <= 400000; i++)
        arbint[i] = 100001;
    for (i = 1; i <= n; i++)
    {
        in >> x;
        a = 1;
        b = n;
        p = 1;
        while (a != b or boo == false)
        {
            arbint[p] = min(arbint[p],x);
            fs = 2 * p;
            fd = 2 * p + 1;
            if (i <= (a + b) / 2)
            {
                p = fs;
                b = (a + b) / 2;
            }
            else
            {
                p = fd;
                a = (a + b) / 2 + 1;
            }
            if (a == b and boo == true)
                boo = false;
            else if (a == b)
                boo = true;
        }
    }
    for (i = 1; i <= m; i++)
    {
        in >> x >> y;
        out << query(x,y,1,n,1) << '\n';
    }
    */
    int x,y,i,j;
    in >> n >> m;
    for (i = 1; i <= n; i++)
    {
        in >> v[i];
        r[0][i] = v[i];
    }
    ln[1] = 0;
    for (i = 2; i <= n; i++)
        ln[i] = 1 + ln[i / 2];
    for (i = 1; i <= ln[n]; i++)
    {
        for (j = 1 << i; j <= n; j++)
            r[i][j] = min(r[i - 1][j],r[i - 1][j - (1 << (i - 1))]);
    }
    for (i = 1; i <= m; i++)
    {
        in >> x >> y;
        out << query(x,y) << '\n';
    }
    return 0;
}