【题意】:给出n个数,求每连续k个数之间的最大最小值。
【题解】:单调队列入门题。
【代码】:
1 #include "iostream"
2 #include "cstdio"
3 #include "cstring"
4 using namespace std;
5 #define maxn 1000500
6 int n, k, val;
7 int maxx[maxn], minn[maxn];
8 int head1, tail1, head2, tail2, tot;
9 struct Drab {
10 int val, idx;
11 Drab(){}
12 Drab(int _val, int _idx) {
13 val = _val, idx = _idx;
14 }
15 }que1[maxn], que2[maxn];
16
17 void init() {
18 tot = 0;
19 head1 = tail1 = head1 = tail1 = 0;
20 }
21
22 void push1(int val, int idx) {
23 while(head1 < tail1 && que1[tail1 - 1].val > val) tail1--;
24 que1[tail1++] = Drab(val, idx);
25 }
26
27 void push2(int val, int idx) {
28 while(head2 < tail2 && que2[tail2 - 1].val < val) tail2--;
29 que2[tail2++] = Drab(val, idx);
30 }
31
32 int main() {
33 while(~scanf("%d%d", &n, &k)) {
34 init();
35 for(int i = 0; i < n; i++) {
36 scanf("%d", &val);
37 push1(val, i), push2(val, i);
38 if(i >= k - 1) {
39 if(que1[head1].idx <= i - k) head1++;
40 minn[tot] = que1[head1].val;
41 if(que2[head2].idx <= i - k) head2++;
42 maxx[tot] = que2[head2].val;
43 tot++;
44 }
45 }
46 for(int i = 0; i < tot; i++) printf("%d ", minn[i]);
47 printf("\n");
48 for(int i = 0; i < tot; i++) printf("%d ", maxx[i]);
49 printf("\n");
50 }
51 return 0;
52 }