POJ2823 http://poj.org/problem?id=2823
最基础的单调队列,说是数据结构,其实就是一种更新数组数据的方法。
之前还准备用deque,超时了,直接head,tail快得多。
一直把删除队首过期元素写在删除队尾之前,就一直WA,尼玛换一下顺序就好了。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 //#define OPEN_FILE 5 using namespace std; 6 const int MAXN = 1000001; 7 int n, w; 8 struct Node{ 9 int v, p; 10 }a[MAXN], d[MAXN]; 11 inline bool cmp(int a, int b){ 12 if (a < b) return true; 13 if (a > b) return false; 14 return false; 15 } 16 void work(bool flag) 17 { 18 int i, head, tail; 19 memset(d, 0, sizeof(d)); 20 head = tail = 1; 21 d[head] = a[1]; 22 for (i = 2; i <= w; i++){ 23 while (cmp(d[tail].v, a[i].v) == flag){ 24 tail--; 25 if (tail < head) break; 26 } 27 d[++tail] = a[i]; 28 } 29 printf("%d", d[head]); 30 for (i = w + 1; i <= n; i++){ 31 if (head <= tail){ 32 while (cmp(d[tail].v, a[i].v) == flag){ 33 tail--; 34 if (head > tail) break; 35 } 36 } 37 d[++tail] = a[i]; 38 while (d[head].p <= i - w){ 39 head++; 40 } 41 printf(" %d", d[head]); 42 } 43 } 44 45 int main() 46 { 47 #ifdef OPEN_FILE 48 freopen("in.txt", "r", stdin); 49 freopen("out.txt", "w", stdout); 50 #endif // OPEN_FILE 51 int i; 52 scanf("%d%d", &n, &w); 53 for (i = 1; i <= n; i++){ 54 scanf("%d", &a[i].v); 55 a[i].p = i; 56 } 57 work(false); 58 printf(" "); 59 work(true); 60 printf(" "); 61 }