Pagini recente » Cod sursa (job #2129052) | Cod sursa (job #2883062) | Cod sursa (job #2097978) | Cod sursa (job #58738) | Cod sursa (job #912312)
Cod sursa(job #912312)
#include <cstdio>
using namespace std;
int n,m,x[100001],mat[100001][21];
void preproc()
{
for(int i=1;i<=n;++i)
mat[i][0]=i;
for(int j=1;(1<<j)<=n;++j)
for(int i=1;i+(1<<j)<=n;++i)
{
if(x[mat[i][j-1]]<x[mat[i+(1<<(j-1))][j-1]])
mat[i][j]=mat[i][j-1];
else mat[i][j]=mat[i+(1<<(j-1))][j-1];
}
}
int lg(int b)
{
int a=0;
while((1<<a)<b)
++a;
if((1<<a)>b)
--a;
return a;
}
int rmq(int a, int b)
{
int log=lg(b-a+1);
int fin=lg(b-a+1-(1<<log));
if(x[mat[a][log]]<x[mat[a+(1<<log)][fin]]||fin<0)
return x[mat[a][log]];
else return x[mat[a+(1<<log)][fin]];
}
void citire()
{
freopen("rmq.in","r",stdin);
freopen("rmq.out","w",stdout);
scanf("%d%d",&n,&m);
for(int i=1;i<=n;++i)
scanf("%d",&x[i]);
int a,b;
preproc();
for(int i=1;i<=m;++i)
{
scanf("%d%d",&a,&b);
printf("%d\n",rmq(a,b));
}
}
int main()
{
citire();
return 0;
}