前言
队列和栈都是重要的数据结构,队列是先进先出,和现实中排队一样,排在前面的先买到。bfs也用到了队列的知识,还是非常重要的。
模拟队列
题目
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 1000010;
int queu[N], hh, tt = -1;
int main()
{
int t;
cin>>t;
while(t--)
{
string op;
cin >> op;
if(op=="push")
{
int x;
cin>>x;
queu[++tt] = x;//进队尾
}
else if(op=="pop")
hh++;//出头
else if(op=="query")
cout << queu[hh] << endl;//输出队首
else
{
if(hh<=tt)
puts("NO");
else
puts("YES");
}
}
}
就是和排队一样。
单调队列(滑动窗口)
这是一个单调队列的经典例题:
题目
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int a[N],q[N];
int main()
{
int n,k;
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;//加一次队列,注意这里存的是i,不是那个数字,当时这里想很久发现是i
if (i >= k - 1)
cout << a[q[hh]] << ' ';//输出头
}
cout << endl;
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]] << ' ';
}
return 0;
}
总结
队列是个非常重要的数据结构,模拟简单,但是单调队列还是偏复杂,需要多加练习!