介绍一种单调栈离线解决RMQ问题的解法。
首先把询问离线下来,按询问的左端点排序。此时每个询问的左端点是单调不降的。考虑用单调栈维护每一段 ,其中 是当前询问的左端点。维护后单调栈的元素是有单调性质的,所以只需要二分找到第一个位置大于等于当前询问右端点的即可。
时间复杂度 ,空间复杂度 。
跑模板的话还是挺快的。
代码
#include<bits/stdc++.h>
using namespace std;
const int N=2e6+7;
const int M=1e5+7;
int n,m,a[M],s[M],tot=0,res[N];
struct ask{int L,R,id;}q[N];
inline int read()
{
int x=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=x*10+ch-48;ch=getchar();}
return x*f;
}
inline bool cmp(ask a,ask b){return a.R<b.R;}
signed main(){
n=read();
m=read();
for(int i=1;i<=n;i++)a[i]=read();
for(int i=1;i<=m;i++)q[i].L=read(),q[i].R=read(),q[i].id=i;
sort(q+1,q+1+m,cmp);
int j=1;
for(int i=1;i<=m;i++){
while(j<=q[i].R){
while(tot&&a[j]>a[s[tot]])tot--;
s[++tot]=j;
j++;
}
int x=lower_bound(s+1,s+1+tot,q[i].L)-s;
// cout<<x<<"\n";
// cout<<q[i].L<<" "<<q[i].R<<"\n";
res[q[i].id]=a[s[x]];
}
for(int i=1;i<=m;i++)printf("%d\n",res[i]);
}