栈与队列
一、模拟栈
1、特性:先进后出
2、模拟栈的操作
int stk[N];//栈数组,从0开始
int tt;//序号
//插入
stk[++tt] = x;
//弹出
tt--;
//判断栈是否为空
if (tt > 0) not empty
else empty
//栈顶
stk[tt];
3、模拟栈
#include <iostream>
uisng namespace std;
const int N = 100010;
int m;
int stk[N], tt;
int main()
{
cin >> m;
while (m--)
{
string op;//字符串op
int x;//操作元素
cin >> op;
if (op == "push")//入栈
{
cin >> x;
stk[++tt] = x;
}
else if (op == "pop") //出栈
tt--;
else if (op == "empty") //判断是否为空
cout << (tt ? "No" : "YES") << endl;
else cout << stk[tt] << endl; //输出栈顶元素
}
return 0;
}
二、模拟队列
1、特点:先进先出,后进后出
2、模拟队列的操作
int q[N];//队列
int hh;//队头
int tt = -1;//队尾,队列从0开始,-1表示为空,
//队尾插入元素
q[++tt] = x;
//弹出队头元素
hh++;
//判断队列是否为空
if (hh <= tt) not empty
else empty
//取出队头元素
q[hh]; //同理可以取出队尾元素 q[tt]
3、模拟队列
#include <iostream>
using namespace std;
const int N = 100010;
int m;
int q[N], hh, tt = -1;
int main(){
cin >> m;
while (m--){
string op;
int x;
cin >> op;
if (op == "push") //入队
{
cin >> x;
q[++tt] = x;
}
else if (op == "pop") //出队
hh++;
else if (op == "empty") //判断队列是否为空
cout << (hh <= tt ? "NO" : "YES") << endl;
else cout << q[hh] << endl; //输出队头元素
}
return 0;
}
三、单调栈
给定一个序列,找到每一个数左边离他最近的比它小的数。
性质:如果 ax >= ay,x < y,那么 ax 永远不会被输出,可以删掉。比如 a3 >= a5,那么 a3 永远不会被输出。
#include <iostream>
using namespace std;
const int N = 10010;
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; //入栈,压入x,形成单调栈
}
return 0;
}
四、单调队列
求滑动窗口里的最大值和最小值。用单调队列来优化。
步骤:
- 判断队头是否已经滑出窗口
- 判断当前元素与队尾元素是否满足单调性问题
- 若满足条件,弹出队尾元素,将当前元素加入队尾
- 如果窗口
【注意】队列里面存的是下标
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 1000010;
int a[N], q[N];
int main(){
int n, k;//窗口长度为k
scanf("%d%d", &n, &k);
for (int i = 0; i < n; i++)
scanf("%d", &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;
//判断是否有前k个数,当窗口长度满足k时,输出队头元素
if (i >= k - 1)
printf("%d ", a[q[hh]]);
}
puts("");
//重置,输出最大值,队列为单调递减
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)
printf("%d ", a[q[hh]]);
}
puts("");
return 0;
}