POJ 2823 单调队列入门水题

最最基础的单调队列题目。一个单增一个单减。还是可以借此好好理解一下单调队列的。

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <iostream>
 4 using namespace std;
 5 
 6 #define maxx 1000005
 7 
 8 int num[maxx], inque[maxx], dque[maxx], maxn[maxx], minn[maxx];
 9 int pre1, pre2, lst1, lst2;
10 int n, k;
11 
12 int main() {
13     while(~scanf("%d%d", &n, &k)) {
14         pre1 = 0, pre2 = 0, lst1 = 0, lst2 = 0;
15         int cnt = 0;
16         for (int i=0; i<n; ++i) {
17             scanf("%d", &num[i]);
18             // 单增
19             while(pre1 < lst1 && num[inque[lst1-1]] > num[i])
20                 lst1--;
21             while(pre2 < lst2 && num[dque[lst2-1]] < num[i])
22                 lst2--;
23             inque[lst1++] = i;
24             dque[lst2++] = i;
25             while(pre1 < lst1 && i - inque[pre1] + 1 > k)
26                 pre1++;
27             while(pre2 < lst2 && i - dque[pre2] + 1 > k)
28                 pre2++;
29             if (i + 1 >= k) {
30                 maxn[cnt] = num[inque[pre1]];
31                 minn[cnt] = num[dque[pre2]];
32                 cnt++;
33             }
34         }
35         for (int i=0; i<cnt-1; ++i) {
36             printf("%d ", maxn[i]);
37         }
38         printf("%d
", maxn[cnt-1]);
39         for (int i=0; i<cnt-1; ++i) {
40             printf("%d ", minn[i]);
41         }
42         printf("%d
", minn[cnt-1]);
43     }
44     return 0;
45 }
View Code
原文地址:https://www.cnblogs.com/icode-girl/p/4865797.html