Cod sursa(job #3222740)

Utilizator tbi1233Tiberiu Telcean tbi1233 Data 11 aprilie 2024 15:38:24
Problema Range minimum query Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <queue>
#include <fstream>

using namespace std;
ifstream fin("rmq.in");
ofstream fout("rmq.out");
typedef pair<int, int> pll;
#define X first
#define Y second
#define r(_x) const _x&
struct cmp{
    operator()(r(pll) a, r(pll) b)
{
    return a.X > b.X;
}
};

typedef priority_queue<pll, vector<pll>, cmp> que;

que pq;
const int Nmax = 100000;
pll arb[Nmax + 10];
    int n;
int v[Nmax];
void buildpq()
{
    for(int i=0; i<n; i++)
    {
        pq.push({v[i], i});
    }
}
void buildarb(que p = pq, int i=1)
{
    que q1, q2;
    pll t = p.top();
    arb[i]=t;
    while(!p.empty())
    {
        pll i = p.top();
        if(i.Y < t.Y)
            q1.push(i);
        else if (i.Y > t.Y)
            q2.push(i);
        p.pop();
    }
    if(!q1.empty())
        buildarb(q1, i*2);
    if(!q2.empty())
        buildarb(q2, i*2 + 1);
}
int m(int a, int b, int i=1)
{
    int y = arb[i].Y;
    if(a <= y && y <= b)
        return arb[i].X;
    if(y < a)
        return m(a, b, 2*i + 1);
    else
        return m(a, b, 2*i);
    return -1;
}

int main()
{
    int q;
    fin >> n >> q;
    for(int i=0; i<n; i++)
        fin >> v[i];
    buildpq();
    buildarb();
    for(int i=0; i<q; i++)
    {
        int a, b;
        fin >> a >> b;
        fout << m(a-1, b-1) << "\n";
    }
    return 0;
}