跳到正文

算法·理论

队列

RKevinR约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年6月6日
更新
2026年6月6日
篇幅
约 3 分钟

版本

  1. v1当前

队列

队列

  队列是一种先进先出(FIFO)的数据结构,元素只能从尾部插入,从队头删除。

  经典应用:广度优先搜索(bfs),多源bfs(从多个起点同时出发), 以及判断只有1长度的单元格最短路径。

  底层是利用deque(双端队列)实现的。

手写模板

手写模板的好处有以下两点:

1.效率会比用STL的内置容器queue会快一点

2.使用起来自由度更高一点,比如可以在执行队列基本操作时同时做前缀和,或者在这个队列上二分等等。

对应题目:https://www.luogu.com.cn/problem/B3616

C++
#include <bits/stdc++.h>
using namespace std;

int q[10005];
// head:队头元素对应数组下标
// tail:队尾元素对应数组下标,从0开始是因为刚开始没有元素
int head = 1, tail = 0;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  
  int n;
  cin >> n;

  while (n--) {
    int op, x;
    cin >> op;
    if (op == 1) {
      // 将x加入队列
      cin >> x;
      q[++tail] = x;
      // 等价于
      // ++tail;
      // q[tail] = x;
    } else if (op == 2) {
      // 说明队列还有元素
      if (head <= tail) {
        // 队头下标往后挪一个,表示弹出一个队头元素
        head++;
      } else {
        cout << "ERR_CANNOT_POP" << '\n';
      }
    } else if (op == 3) {
      // 说明队列还有元素
      if (head <= tail) {
        cout << q[head] << '\n';
      } else {
        cout << "ERR_CANNOT_QUERY" << '\n';
      }
    } else {
      // 队内元素所在区间 = [head, tail]
      // 队内元素个数 = tail - head + 1;
      cout << tail - head + 1 << '\n';
    }
  }
  return 0;
}

内置STL容器queue

queue基本操作

C++
queue<数据类型> q;

// 在队尾插入x这个元素
q.push(x);

// 弹出队头元素,需要检查是否队列为空
q.pop();

// 返回队内元素个数
q.size();

// 返回队首元素
q.front();

// 返回队尾元素
q.back();

// 队列是否为空,空则返回true,非空返回false
q.empty();

扩展

模板队列

https://www.luogu.com.cn/problem/B3616 https://www.luogu.com.cn/problem/AT_abc389_c

双向bfs

https://www.luogu.com.cn/problem/P1032 https://www.luogu.com.cn/problem/P1379

思维bfs

https://www.luogu.com.cn/problem/AT_abc460_d

优化建图

https://www.luogu.com.cn/problem/P3921

持续更新中!!!

原文