Pagini recente » Cod sursa (job #584309) | Cod sursa (job #1963160) | Cod sursa (job #585899) | Cod sursa (job #1868054) | Cod sursa (job #1051967)
// 7.12.2013
// Range Minimium Query
// O(N) -> Pre-processing time
// O(sqrt(N)) -> Query time
using namespace std;
#include<fstream>
#include<cmath>
#include<algorithm>
ifstream cin("rmq.in");
ofstream cout("rmq.out");
const int MAXN=100000;
int main(){
int A[MAXN];
int M[(int)sqrt(MAXN)];
int N;
// Pre-processing the array
int K;
cin>>N;
cin>>K;
int k=sqrt(N);
for(int i=0;i<N;i++)
cin>>A[i];
int j=0; //The counter for the parts of size sqrt(N)
for(int i=0;i<N;i++){
if(i==k*(j+1)){ //We have reached the next part of size sqrt(N)
j++;
M[j]=i;
}else{
if(A[M[j]]>A[i])
M[j]=i;
} //We are still in this part of size sqrt(N)
}
//The Query Part
for(int l=1;l<=K;l++){
int x,y;
cin>>x>>y;
x--; y--;
int mnm=x; //we set the minimum to something equivalent ot infinity
int j=x/k;
if(j<x) j++;
int lf,rt;
lf=k*j-1;
rt=y/k;
for(;(j+1)*k-1<=y;j++)// we search the whole parts of size sqrt(N) that are in the interval [x,y]
if(A[mnm]>A[M[j]])
mnm=M[j];
for(int t=x;t<=max(lf,y);t++)// we search for the numbers that are at the edge of the interval [x,y]
if(A[mnm]>A[t])
mnm=t;
for(int t=max(rt*k,x);t<=y;t++)
if(A[mnm]>A[t])
mnm=t;
cout<<A[mnm]<<'\n';
}
return 0;
}