学习顺序:

  1. 学会使用STL的基本用法
  2. 学会使用STL解决问题
  3. 学会用一维数组模拟队列,解决问题

队列是限定在一端进行插入,另一端进行删除的特殊线性表

queue q

  1. queue<int> q;
  2. q.push(3);
  3. q.push(2);
  4. q.push(5);
  5. cout << q.front(); // 3
  6. q.pop();
  7. cout << q.front(); // 2

例题,2037:【例5.4】约瑟夫问题

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int main()
  4. {
  5. int n, m;
  6. cin >> n >> m;
  7. queue<int> q;
  8. for (int i = 1; i <= n; i++) q.push(i);
  9. int k = 0;
  10. while (!q.empty()){
  11. k++;
  12. int t = q.front(); q.pop();
  13. if (k == m){
  14. k = 0;
  15. printf("%d ", t);
  16. continue;
  17. }
  18. q.push(t);
  19. }
  20. puts("");
  21. return 0;
  22. }

一维数组模拟队列

https://www.acwing.com/problem/content/831/
image.png
image.png

  1. // 初始化,int hh = 0, tt = -1; //Think about it: 莫队不也是这样吗?
  2. #include <iostream>
  3. using namespace std;
  4. const int N = 100010;
  5. int q[N];
  6. int hh = 0, tt = -1;
  7. int main()
  8. {
  9. int M;
  10. cin >> M;
  11. string op;
  12. int x;
  13. while (M--)
  14. {
  15. cin >> op;
  16. if (op == "push")
  17. {
  18. cin >> x;
  19. q[++tt] = x;
  20. }
  21. if (op == "pop")
  22. {
  23. hh++;
  24. }
  25. if (op == "query")
  26. {
  27. cout << q[hh] << endl;
  28. }
  29. if (op == "empty")
  30. {
  31. if (hh <= tt) cout << "NO" << endl;
  32. else cout << "YES" << endl;
  33. }
  34. }
  35. return 0;
  36. }

例题,【例2-3】围圈报数

  1. //用queue模拟出圈的过程

例题,猴子选大王

  1. //一般的猴子选大王,约瑟夫环问题,都是玩一个游戏,数一个固定的数m,数到就出圈
  2. //这道题目是,从i个猴子开始数,就使用第i个规则数
  3. //所以,这点在模拟的时候会不同。其他和普通的约瑟夫一样

例题,【例2-1】周末舞会

  1. //模拟两个队伍循环的过程,用两个指针模拟

例题,产生数(Produce)

  1. //这道题目的规则是一位数字,转换成一位数字
  2. //不是多位的转换,没那么复杂,可以直接暴力的干
  3. //遇到坑,还是要多变换姿势求解
  4. //最开始,我自己分析题意是,转换规则,可能是 ab -> cdd,这种变态的模式
  5. //然后我就写了1个小时而已,写不出来了。主要是控制不好字符串替换中间一段的操作,存在开头和去尾的特殊位置
  6. //感觉,这样出测试用例,肯定是一道好模拟题