单调栈模板

题目

单调栈模板

时间复杂度:\(O(n)\)

#include<bits/stdc++.h>
using namespace std;
const int N=3e6+5;
int n,a[N],f[N];
stack<int> s;
int main(){
	ios::sync_with_stdio(0);cin.tie(0);
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>a[i];
	}
	for(int i=n;i>=1;i--){
		while(s.size()&&a[s.top()]<=a[i]){
			s.pop();//将右侧小于等于靠左侧(且更大或等于)的数弹出
		}
		f[i]=s.size()?s.top():0;
		s.push(i);//存下标
	}
	for(int i=1;i<=n;i++){
		cout<<f[i]<<' ';
	}
	return 0;
}
posted @ 2026-08-09 07:58  decentz  阅读(12)  评论(0)    收藏  举报