栈和队列基本函数
#include 栈的头文件
#include 队列的头文件
定义栈如下:
stack s;
定义队列如下:
queue q;
栈的基本操作
s.empty() 如果栈为空返回true,否则返回false
s.size() 返回栈中元素的个数
s.pop() 删除栈顶元素但不返回其值
s.top() 返回栈顶的元素
s.push() 在栈顶压入新元素
队列的基本操作
q.empty() 如果队列为空返回true,否则返回false
q.size() 返回队列中元素的个数
q.pop() 删除队列首元素但不返回其值
q.front() 返回队首元素的值
q.push() 在队尾压入新元素
q.back() 返回队列尾元素的值,但不删除该元素
单调栈
常见模型:给定一个序列,求每一个数的左边离他最近的且比它小的数。
每个·答案一定是最右边的,寻找一个都比给定值小的单调递增序列,最栈顶就是要求的值,不满足的值弹出即可
代码
# include <iostream>
# include <stack>
using namespace std;
const int N = 1e5 + 10;
stack<int> a;
int main(){
int n;
cin >> n;
int x;
for (int i = 0 ; i < n ; i ++){
cin >> x;
// 当栈不为空且栈顶大于x,弹出栈顶,维持单调性
while (!a.empty() && x <= a.top()) a.pop();
// 当栈为空,不存在小于x的值
if (a.empty()) cout << -1 << " ";
// 当栈不为空,输出栈顶
else cout << a.top() <<" ";
// 每次更新栈顶
a.push(x);
}
return 0;
}
单调队列
解决滑动窗口问题,解决区间内极值问题,若要维护单调递增队列,那么对头就是极小值,反之,维护的单调递减序列,队头元素就是极大值
# include <iostream>
# include <queue>
using namespace std;
const int N = 1e6 + 10;
int a[N],q[N];//q[N]存的是数组下标
int main(){
int n , k;
cin >> n >> k;
int hh = 1 , tt = 0;
for (int i = 1; i <= n; i++){
cin >> a[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) cout << a[q[hh]] << " ";
}
cout << endl;
hh = 1 , tt = 0;
memset(q, 0, sizeof(q));
for (int i = 1; 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) cout << a[q[hh]] << " ";
}
return 0;
}