单调栈(ACWing

原题链接

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int maxn=1e5+5;
 4 int n,a[maxn],ans[maxn],sta[maxn];
 5 int tot;
 6 int main(){
 7     scanf("%d",&n);
 8     for(int i=1;i<=n;i++){
 9         scanf("%d",&a[i]);
10     }
11     for(int i=1;i<=n;i++){
12         while(tot&&sta[tot]>=a[i])tot--;
13         if(tot){
14             printf("%d ",sta[tot]);
15             sta[++tot]=a[i];//记得把符合单调性的元素入栈
16         }
17         else{
18             sta[++tot]=a[i];
19             printf("-1 ");
20         }
21     }
22     return 0;
23 }

 

posted @ 2022-09-14 17:00  九州霜  阅读(21)  评论(0编辑  收藏  举报