poj 2823 Sliding Window 单调队列(裸题)

单调队列,名叫队列,但与队列不太相同,入队同样从队尾进,但出队可以从队头弹出,也可以在队尾删去

一般有单调递增队列和单调递减队列

这里以单调递增队列为例

1.入队:把该入队的元素a与队尾元素比较,如果队尾元素大于a,则减小尾指针,将该元素删去,重复该步骤,直到队列为空或是队尾元素小于a,再把a入队

2.出队:分从队头弹出和队尾删去,队尾删去即为入队时会涉及的操作。当队列长度一定时,若队列长度大于则增加头指针,弹出队头的元素

时间复杂度O(n)

一道裸题练下板子

Sliding Window

Time Limit: 12000MS   Memory Limit: 65536K
Total Submissions: 70143   Accepted: 19917
Case Time Limit: 5000MS

Description

An array of size n ≤ 106 is given to you. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves rightwards by one position. Following is an example: 
The array is [1 3 -1 -3 5 3 6 7], and k is 3.

Window position Minimum value Maximum value
[1  3  -1] -3  5  3  6  7  -1 3
 1 [3  -1  -3] 5  3  6  7  -3 3
 1  3 [-1  -3  5] 3  6  7  -3 5
 1  3  -1 [-3  5  3] 6  7  -3 5
 1  3  -1  -3 [5  3  6] 7  3 6
 1  3  -1  -3  5 [3  6  7] 3 7

Your task is to determine the maximum and minimum values in the sliding window at each position. 

Input

The input consists of two lines. The first line contains two integers n and k which are the lengths of the array and the sliding window. There are n integers in the second line. 

Output

There are two lines in the output. The first line gives the minimum values in the window at each position, from left to right, respectively. The second line gives the maximum values. 

Sample Input

8 3
1 3 -1 -3 5 3 6 7

Sample Output

-1 -3 -3 -3 3 3
3 3 5 5 6 7

代码:

//#include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const  int maxx=1e6+100;
const int INF=1e9;
const int MOD=1e9+7;
int a[maxx];
int Max[maxx],Min[maxx];
int n,k;
int in[maxx],de[maxx];
void getmin()
{
    int tail=-1,head=0;
    int cnt=0;
    for(int i=1; i<=n; i++){
        while(head<=tail && a[i]<=a[de[tail]])  tail--;
        de[++tail]=i;
        while(de[head] < i-k+1) head++;
        if(i>=k){
            Min[++cnt]=a[de[head]];
        }
    }
    for(int i=1; i<=cnt; i++){
        if(i==1)  printf("%d",Min[i]);
        else      printf(" %d",Min[i]);
    }
    printf("\n");
}
void getmax()
{
    int tail=-1,head=0;
    int cnt=0;
    for(int i=1; i<=n; i++){
        while(head<=tail && a[i]>=a[in[tail]])  tail--;
        in[++tail]=i;
        while(in[head]<i-k+1)  head++;
        if(i>=k){
            Max[++cnt]=a[in[head]];
        }
    }
    for(int i=1; i<=cnt; i++){
        if(i==1)  printf("%d",Max[i]);
        else      printf(" %d",Max[i]);
    }
    printf("\n");
}
int main()
{
    while(~scanf("%d%d",&n,&k)) {
        for (int i = 1; i <= n; i++)
            scanf("%d",&a[i]);
        getmin();
        getmax();
    }
    return 0;
}

 

posted @ 2018-08-04 16:10  任小喵  阅读(102)  评论(0编辑  收藏  举报