单调栈,单调队列

单调栈,单调队列

单调栈

常用题型:给定一个序列,在这个序列,每一个序列左边,离它最近的比它大或者比它小的数在什么地方。

#include <iostream>
#include <vector>
using namespace std;

const int N = 1e5 + 10;
int n;

int stk[N], tt;

int main()
{
    
    
    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;
    }
}

单调队列

用滑动窗口找序列中的最小值

#include <iostream>
#include <vector>
using namespace std;

const int N = 1e5 + 10;
int n;
int a[N], q[N];
int k;
int main()
{
    
    
    cin >> n >> k;
    for(int i = 0; i < n; i ++) cin >> a[i];
    int hh = 0, tt = -1;
    for(int i = 0; i < n; i ++)
    {
    
    
        //判断队头是否已经滑出窗口
        if(hh <= tt && i - k + 1 > q[hh]) hh ++; 
        while(hh <= tt && a[q[tt]] >= a[i]) tt --;
        q[++ tt] = i;
        if(i >= k - 1) cout << a[q[hh]] << ' ';
    }
    cout << endl;
}

猜你喜欢

转载自blog.csdn.net/qq_47783181/article/details/112873149