Sliding Window POJ

来源:互联网 发布:vb编程实例 编辑:程序博客网 时间:2024/06/15 01:39

题目链接:点我


    An array of size n ≤ 10 6 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 31 3 -1 -3 5 3 6 7

Sample Output

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

题意:

给你n个数,你有一个大小为k的窗口从左向右滑动,求每次窗口内数的最大值和最小值.

思路:

单调队列,维护两个单调队列,分别求最大值和最小值,单调队列中的元素下标不能超过k即可

代码:

#include<cstring>#include<cstdio>#include<algorithm>#include<cmath>#include<iostream>using namespace std;const int maxn = 1e6 +10;int a[maxn];int maxi[maxn];int maxj[maxn];int mini[maxn];int minj[maxn];int ans[maxn];int n, w;void getmax(){    int k=0;    for(int i = 1; i <= w; ++ i){        while(k > 0 && a[i] >= maxi[k]) --k;        maxi[++k] = a[i];        maxj[k] = i;    }    printf("%d", maxi[1]);    int l = 1;    for(int i = w + 1; i <= n; ++ i){        if(w < i - maxj[l] +1) ++l;        while(k >= l && a[i] >= maxi[k]) --k;        maxi[++k] = a[i];        maxj[k] = i;        printf(" %d",maxi[l]);    }    printf("\n");}void getmin(){    int k=0;    for(int i = 1; i <= w; ++ i){        while(k > 0 && a[i] <= mini[k]) --k;        mini[++k] = a[i];        minj[k] = i;    }    printf("%d", mini[1]);    int l = 1;    for(int i = w + 1; i <= n; ++ i){        if(w < i - minj[l] +1) ++l;        while(k >= l && a[i] <= mini[k]) --k;        mini[++k] = a[i];        minj[k] = i;        printf(" %d",mini[l]);    }    printf("\n");}int main(){   while (scanf("%d %d", &n, &w) != EOF){    for(int i = 1; i <= n; ++ i)        scanf("%d", &a[i]);    getmin();    getmax();   }}
原创粉丝点击