mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4
143 字
1 分钟
数据结构-单调栈
2026-08-12

单调栈可以是

  • 从栈底往栈顶严格递增
  • 从栈底往栈顶严格递减

最经典的用法是为了解决类似求数组中一个数左右比它大(小)且离它位置最近的数的下标的问题

如果存在数值相等的情况需要特殊处理

模板#

P5788 【模板】单调栈 - 洛谷#

int n;
stack<int> st;
void solve() {
cin>>n;
vector<int> a(n+1),res(n+1);
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=1;i<=n;i++){
while(!st.empty()&&a[st.top()]<a[i]){
res[st.top()]=i;
st.pop();
}
st.push(i);
}
while(!st.empty()){
res[st.top()]=0;
st.pop();
}
for(int i=1;i<=n;i++){
cout<<res[i]<<" ";
}
}

单调栈结构(进阶)_牛客题霸_牛客网#

int n;
void solve() {
cin>>n;
vector<int> a(n),b(n),c(n);
for(int i=0;i<n;i++){
cin>>a[i];
}
stack<int> st;
for(int i=0;i<n;i++){
while(!st.empty()&&a[i]<=a[st.top()]){
int x=st.top();
st.pop();
b[x]=(st.empty()?-1:st.top());
c[x]=i;
}
st.push(i);
}
while(!st.empty()){
int x=st.top();
st.pop();
b[x]=(st.empty()?-1:st.top());
c[x]=-1;
}
for(int i=0;i<n;i++){
while(a[c[i]]==a[i]){ // 处理相等值的代码
c[i]=c[c[i]];
}
cout<<b[i]<<" "<<c[i]<<"\n";
}
}

例题#

P2866 [USACO06NOV] Bad Hair Day S - 洛谷#

3.探究子序列【算法赛】 - 蓝桥云课#

分享

如果这篇文章对你有帮助,欢迎分享给更多人!

数据结构-单调栈
https://blog.hydrodyio.xyz/posts/数据结构-单调栈/
作者
Hydroiody
发布于
2026-08-12
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

目录