C101【模板】单调栈 P5788 单调栈

C101【模板】单调栈 P5788 单调栈_哔哩哔哩_bilibili

 

C15【模板】单调队列 滑动窗口最值 - 董晓 - 博客园 (cnblogs.com)

P5788 【模板】单调栈 - 洛谷

P2947 [USACO09MAR] Look Up S - 洛谷

// 单调栈 O(n)
#include<bits/stdc++.h>
using namespace std;

const int N=3000005;
int n,a[N],ans[N];

int main(){
  scanf("%d",&n);
  for(int i=1;i<=n;i++) scanf("%d",&a[i]);
  
  int s[N],top=0;
  for(int i=1; i<=n; i++){
    while(top && a[s[top]]<a[i]){
      ans[s[top]]=i; //i高于栈顶,记答案、出栈
      top--;
    } 
    s[++top]=i; //i低于栈顶,入栈
  }
  
  for(int i=1;i<=n;i++) printf("%d ",ans[i]);
}

  

P2866 [USACO06NOV] Bad Hair Day S - 洛谷

#include<bits/stdc++.h>
using namespace std;

const int N=1000010;
int n,h[N];
int top,s[N];
long long ans;

int main(){
  cin>>n;
  for(int i=1; i<=n; i++) cin>>h[i];
  
  for(int i=1; i<=n; i++){
    while(top &&h[s[top]]<=h[i]) top--;
    ans+=top; //栈中前面高的都能看见i
    s[++top]=i;
  }
  cout<<ans;
}

 

P8094 [USACO22JAN] Cow Frisbee S - 洛谷

#include<bits/stdc++.h>
using namespace std;

const int N=1000010;
int n,h[N];
int top,s[N];
long long ans;

int main(){
  cin>>n;
  for(int i=1; i<=n; i++) cin>>h[i];
  
  for(int i=1; i<=n; i++){
    while(top &&h[s[top]]<h[i]){
      ans+=i-s[top]+1; //与栈中前面低的配对
      top--;
    }
    if(top) ans+=i-s[top]+1; //与栈中前面一个高的配对
    s[++top]=i;
  }
  cout<<ans;
}

 

P8082 [COCI 2011/2012 #4] KEKS - 洛谷

#include<bits/stdc++.h>
using namespace std;

#define N 500005
char s[N];
int n,k,stk[N],top;

int main(){
  scanf("%d%d%s",&n,&k,s+1);
  for(int i=1;i<=n;i++){
    int x=s[i]-'0';
    while(k&&top&&stk[top]<x) k--,top--; //数变大时出栈
    stk[++top]=x; //数变小时入栈
  }
  for(int i=1;i<=top-k;i++) printf("%d",stk[i]);
}

 

posted @ 2024-03-15 10:55  董晓  阅读(679)  评论(0)    收藏  举报