A - Sliding Window POJ - 2823

Posted dreamkill

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了A - Sliding Window POJ - 2823相关的知识,希望对你有一定的参考价值。

http://poj.org/problem?id=2823// 原题链接

 

技术分享图片

 

题目大意,就是输出每个相邻 (i,i+k+1)区间中的最大值

/// 单调队列练习

 

 

技术分享图片
 1 #include <algorithm>
 2 #include <stack>
 3 #include <istream>
 4 #include <stdio.h>
 5 #include <map>
 6 #include <math.h>
 7 #include <vector>
 8 #include <iostream>
 9 #include <queue>
10 #include <string.h>
11 #include <set>
12 #include <cstdio>
13 #define FR(i,n) for(int i=0;i<n;i++)
14 #define MAX 2005
15 #define mkp pair <int,int>
16 using namespace std;
17 #pragma comment(linker, "/STACK:10240000000,10240000000")
18 const int maxn = 1e6+5;
19 typedef long long ll;
20 const int  inf = 0x3fffff;
21 void read(int  &x) {
22     char ch; bool flag = 0;
23     for (ch = getchar(); !isdigit(ch) && ((flag |= (ch == -)) || 1); ch = getchar());
24     for (x = 0; isdigit(ch); x = (x << 1) + (x << 3) + ch - 48, ch = getchar());
25     x *= 1 - 2 * flag;
26 }
27 int val[maxn];
28 int Min[maxn],Max[maxn];
29 int id[maxn],path[maxn];
30 int main() {
31  int n,m;
32     while(~scanf("%d%d",&n,&m)){
33         vector <int> r1;
34         vector <int> r2;
35         for(int i=0;i<n;i++)read(val[i]);
36         int tail = 1, ed = 0;
37         int head = 1, sd = 0;
38         for(int i=0;i<m-1;i++){
39             while(val[i]<=Min[ed]&&tail<=ed){
40                 --ed;
41             }
42 
43             while(val[i]>=Max[sd]&&head<=sd){
44                 --sd;
45             }
46             path[++sd]=i;
47             Max[sd]=val[i];
48 
49             id[++ed]=i;
50             Min[ed]=val[i];
51 
52         }
53     //    r2.push_back(Max[head]);
54      //   r1.push_back(Min[tail]);
55         for(int i=m-1;i<n;i++){
56            //for(int j=tail;j<=ed;j++)printf("%d ",Min[j]);
57           // puts("");
58             while(val[i]<=Min[ed]&&tail<=ed){
59                 ed--;
60             }
61 
62 
63             while(val[i]>=Max[sd]&&head<=sd){
64                 sd--;
65             }
66 
67             path[++sd]=i;
68             Max[sd]=val[i];
69             while(i-path[head]+1>m)head++;
70             r2.push_back(Max[head]);
71 
72             id[++ed]=i;
73             Min[ed]=val[i];
74             while(i-id[tail]+1>m)
75             {
76                 tail++;
77             }
78             r1.push_back(Min[tail]);
79         }
80         int siz = r1.size();
81         for(int i=0;i<siz;i++){
82             printf("%d%c",r1[i],(i==(siz-1)?
: ));
83         }
84         for(int i=0;i<siz;i++){
85             printf("%d%c",r2[i],(i==(siz-1)?
: ));
86         }
87     }
88     return 0;
89 }
View Code

 

以上是关于A - Sliding Window POJ - 2823的主要内容,如果未能解决你的问题,请参考以下文章

poj2823Sliding Window——单调队列

poj 2823 Sliding Window

POJ 2823 Sliding Window 题解

POJ 2823 Sliding Window

POJ 2823 Sliding Window

POJ2823 Sliding Window