板子
模拟队列
829. 模拟队列
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
int n;
int tt, hh;
int q[N];
void init()
{
hh = tt = 0;
}
int main()
{
init();
cin >> n;
while(n -- )
{
string op;
int x;
cin >> op;
if(op == "push")
{
cin >> x;
q[tt ++] =x;
} else if(op == "pop")
{
hh ++ ;
} else if(op == "query")
{
cout << q[hh] << endl;
} else {
if(hh == tt) puts("YES");
else puts("NO");
}
}
return 0;
}
注意
- 模拟队列中,队尾在后面,队头靠近0
- 队尾加数向右走, 队头加数向右走
总结
// 初始化队列
hh = tt = 0;
// 队尾插入一个数
q[tt ++] =x;
// 队头弹出一个数
hh ++ ;
// 查询对头元素
q[hh]
// 判断是否为空
hh == tt
单调队列
154. 滑动窗口
#include <iostream>
using namespace std;
const int N = 1e6 + 10;
int n, k;
int a[N], q[N];
int main()
{
scanf("%d%d", &n, &k);
for(int i = 0; i < n; i ++ ) scanf("%d", &a[i]);
int tt = -1, hh = 0;
for(int i = 0; i < n; i ++)
{
if(hh <= tt && q[hh] < i - k + 1 ) hh ++ ;
while(hh <= tt && a[q[tt]] >= a[i]) tt -- ;
q[++ tt] = i;
if(i >= k - 1) printf("%d ", a[q[hh]]);
}
puts("");
hh = 0, tt = -1;
for(int i = 0; i < n; i ++ )
{
if(hh <= tt && q[hh] < i - k + 1) hh ++ ;
while(hh <= tt && a[q[tt]] <= a[i]) tt --;
q[++ tt ] = i;
if(i >= k - 1) printf("%d ", a[q[hh]]);
}
return 0;
}
总结
注意