P5788(洛谷)
P5788 单调栈
思路:
维护一个单调递减的栈,重复执行:当入栈的下标所对应的值,那么入栈的下标为栈顶下标的f(x)的值,存入ans函数,并弹出栈顶元素。
代码:
#include<bits/stdc++.h>
using namespace std;
stack<int> w;
int a[3000005],ans[3000005];
int n;
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<=n;i++){
while(!w.empty()){
if(a[w.top()]<a[i]){
ans[w.top()]=i;
w.pop();
}
else break;
}
w.push(i);
}
while(!w.empty()){
ans[w.top()]=0;
w.pop();
}
for(int i=1;i<=n;i++)
cout<<ans[i]<<" ";
return 0;
}