单调栈题目

1.给定一个长度为 N 的整数数列,输出每个数左边第一个比它小的数,如果不存在则输出 −1。

  • 输入格式
    第一行包含整数 N,表示数列长度。

    第二行包含 N 个整数,表示整数数列。

  • 输出格式
    共一行,包含 N 个整数,其中第 i 个数表示第 i 个数的左边第一个比它小的数,如果不存在则输出 −1。

  • 数据范围
    1≤N≤105
    1≤数列中元素≤109

题目链接:https://www.acwing.com/problem/content/description/832/

#include

using namespace std;

const int N=10010;

int stk[N],tt;

int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        int x;
        cin>>x;
        while(tt&&stk[tt]>=x) tt--;
        if(tt) cout<<stk[tt]<<' ';
        else cout<<-1<<' ';
        
        stk[++tt]=x;
    }
    
    
}

2.和上题类似,但是要求的是每个数右边第一个比它大的数的下标,若没有比它大的数则为0。

样例:
输入

5
1 4 2 3 5

输出

2 5 4 5 0

题目链接:https://www.luogu.com.cn/problem/P5788

#include

using namespace std;
const int N = 3000010;
int stk[N],tt,a[N],res[N];

int main()
{
    int n;
    cin>>n;
    for(int i = 1; i <= n;i++) cin>>a[i];
    for(int i = 1;i <= n/2;i++) swap(a[i],a[n+1-i]);
    for(int i = 1;i<=n;i++)
    {
        while(tt && a[stk[tt]]<=a[i]) tt--;
        if(tt) res[i] = n + 1 -stk[tt];
        else res[i] = 0;
        stk[++tt] = i;
    }
    for(int i = n;i>=1;i--) cout<<res[i]<<" ";
}

你可能感兴趣的:(杂记,c++,算法)