POJ2823 Sliding Window

  原题传送:http://poj.org/problem?id=2823

  单调队列练手题。(不怕麻烦也可以用线段树)

  程序运行了5000+ms,不明白几百ms的是什么算法,如果读者您知道请留个言,感激不尽。

View Code
 1 #include <stdio.h>
 2 #include <string.h>
 3 #define N 1000005
 4 int a[N];
 5 
 6 struct node
 7 {
 8     int key, val;
 9 }e[1000005];
10 
11 
12 int main()
13 {
14     int n, k, i, head, tail;
15     while(scanf("%d%d", &n, &k) != EOF)
16     {
17         for(i = 1; i <= n; i ++)
18             scanf("%d", &a[i]);
19         
20         for(head = tail = i = 1; i < k; i ++)
21         {
22             while(head <= tail && e[tail].val > a[i])
23                 tail --;
24             e[++tail].key = i;
25             e[tail].val = a[i];
26         }
27         for(i = k; i <= n; i ++)
28         {
29             while(head <= tail && e[head].key + k - 1 < i)
30                 head ++;
31             while(head <= tail && e[tail].val > a[i])
32                 tail --;
33             e[++tail].key = i;
34             e[tail].val = a[i];
35             printf("%d%s", e[head].val, i == n ? "" : " ");
36         }
37         putchar('\n');
38         
39         
40         for(head = tail = i = 1; i < k; i ++)
41         {
42             while(head <= tail && e[tail].val < a[i])
43                 tail --;
44             e[++tail].key = i;
45             e[tail].val = a[i];
46         }
47         for(i = k; i <= n; i ++)
48         {
49             while(head <= tail && e[head].key + k - 1 < i)
50                 head ++;
51             while(head <= tail && e[tail].val < a[i])
52                 tail --;
53             e[++tail].key = i;
54             e[tail].val = a[i];
55             printf("%d%s", e[head].val, i == n ? "" : " ");
56         }
57         putchar('\n');
58     }
59     return 0;
60 }

你可能感兴趣的:(window)