单调栈模板
单调栈模板
时间复杂度:\(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;
}

浙公网安备 33010602011771号