poj 2823 Sliding Window 【固定区间长度的RMQ】 【二维压缩成一维】

来源:互联网 发布:电力工程结算软件 编辑:程序博客网 时间:2024/06/06 00:33
Sliding Window
Time Limit: 12000MS Memory Limit: 65536KTotal Submissions: 47090 Accepted: 13602Case 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 positionMinimum valueMaximum value[1  3  -1] -3  5  3  6  7 -13 1 [3  -1  -3] 5  3  6  7 -33 1  3 [-1  -3  5] 3  6  7 -35 1  3  -1 [-3  5  3] 6  7 -35 1  3  -1  -3 [5  3  6] 7 36 1  3  -1  -3  5 [3  6  7]37

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 3

3 3 5 5 6 7

题意:给你一个N个数的序列,并固定连续区间长度为k。现让你依次求出所有长度为k的连续区间里面 的最大值和最小值。

思路:裸RMQ,但使用二维会MLE。由于题目已经固定了区间长度k,也就是说我们只需要使用区间长度为k时的信息。我们可以用一维数组按长度递增来推出区间长度为k值的信息。

预处理数组Amax[i]和Amin[i]之后,它们分别存储的是以A[i]开始的,长度为k的连续区间里面的最大值和最小值。

压缩空间思路点这里:点我

AC代码:

#include <cstdio>#include <cstring>#include <algorithm>#define MAXN 1000000+10using namespace std;int N, k;int A[MAXN];int Amax[MAXN];int Amin[MAXN];void RMQ_init(){    for(int i = 1; i <= N; i++)        Amax[i] = Amin[i] = A[i];    for(int j = 1; (1<<j) <= k; j++)    {        for(int i = 1; i + (1<<j) - 1 <= N; i++)        {            Amax[i] = max(Amax[i], Amax[i + (1<<(j-1))]);            Amin[i] = min(Amin[i], Amin[i + (1<<(j-1))]);        }    }}int query(int L, int R, int mark){    int len = 0;    while(1<<(len+1) <= R-L+1) len++;    if(mark == 1)        return max(Amax[L], Amax[R-(1<<len)+1]);    else        return min(Amin[L], Amin[R-(1<<len)+1]);}int main(){    while(scanf("%d%d", &N, &k) != EOF)    {        for(int i = 1; i <= N; i++)            scanf("%d", &A[i]);        RMQ_init();        for(int i = 1; i <= N-k+1; i++)        {            if(i > 1) printf(" ");            printf("%d", query(i, i+k-1, 2));        }        printf("\n");        for(int i = 1; i <= N-k+1; i++)        {            if(i > 1) printf(" ");            printf("%d", query(i, i+k-1, 1));        }        printf("\n");    }    return 0;}




0 0
原创粉丝点击