1.题目链接
Sliding Window
2.题意
给你一个长度为n的数列,要求求出每个连续的长度为m的字串的最大值和最小值。
3.解法
单调队列的简单应用
4.代码
# include <cstdio> int v[1111111]; int deq[1111111], head, tail; int main(){ // std::ios::sync_with_stdio(false);cin.tie(0); int n, w; while (~scanf("%d%d", &n, &w)){ for (int i = 0; i < n; i++) scanf("%d", &v[i]); int s, e; s = e = 0; head = tail = 0; while (s + w <= n){ while (e-s<w) { while (tail > head && v[e] < v[deq[tail-1]]){ --tail; } deq[tail++] = e++; } printf("%d%c", v[deq[head]], s==n-w?'\n':' '); s++; if (deq[head] < s) head++; } s = e = 0; head = tail = 0; while (s + w <= n){ while (e-s<w) { while (tail > head && v[e] > v[deq[tail-1]]){ --tail; } deq[tail++] = e++; } printf("%d%c", v[deq[head]], s==n-w?'\n':' '); s++; if (deq[head] < s) head++; } } return 0; }