跳到正文

个人记录

浅谈单调栈解决RMQ问题

Cute_Fish约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年7月10日
篇幅
约 2 分钟

版本

  1. v1当前

介绍一种单调栈离线解决RMQ问题的解法。

首先把询问离线下来,按询问的左端点排序。此时每个询问的左端点是单调不降的。考虑用单调栈维护每一段 1≤j≤R1\leq j \leq R,其中 RR 是当前询问的左端点。维护后单调栈的元素是有单调性质的,所以只需要二分找到第一个位置大于等于当前询问右端点的即可。

时间复杂度 O(qlog⁡q+qlog⁡n)O(q\log q+q\log n),空间复杂度 O(n)O(n)。

跑模板的话还是挺快的。

代码

C++
#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]);
}
原文
存档评论2 条抓取于