Pagini recente » Cod sursa (job #1171413) | Cod sursa (job #1367717) | Cod sursa (job #628207) | Cod sursa (job #1610702) | Cod sursa (job #3222741)
#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{
bool 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;
}