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

  1. 思考过程
  2. 1.暴力怎么做
  3. 2.队列当中有没有无用的值,怎么去掉
  4. 3.删掉多余的值,构造单调性
  5. 4.有了单调性,就有了极值,就优化了问题

image.png
image.png

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int N = 1e6 + 10;
  4. int n, k;
  5. int a[N], q[N];
  6. int main()
  7. {
  8. cin >> n >> k;
  9. for (int i = 0; i < n; i++) scanf("%d", &a[i]);
  10. int hh = 0, tt = -1;
  11. for (int i = 0; i < n; i++)
  12. {
  13. if (hh <= tt && i - k + 1 > q[hh]) hh++; //队列中有值&& 队头超出窗口左端
  14. while (hh <= tt && a[q[tt]] >= a[i]) tt--; //q[]存在的是下标,如果要拿值,还要再套一层a[ ]
  15. q[++tt] = i;
  16. if (i >= k - 1)printf("%d ", a[q[hh]]); //窗口里的数要有k个才可以输出,i从0开始计数
  17. }
  18. puts("");
  19. hh = 0, tt = -1;
  20. for (int i = 0; i < n; i++)
  21. {
  22. if (hh <= tt && i - k + 1 > q[hh]) hh++; //队头滑出窗口
  23. while (hh <= tt && a[q[tt]] <= a[i]) tt--;
  24. q[++tt] = i;
  25. if (i >= k - 1)printf("%d ", a[q[hh]]);
  26. }
  27. puts("");
  28. return 0;
  29. }

例题,NBUT - 1021