poj2823

来源:互联网 发布:苏州飚风软件注册码 编辑:程序博客网 时间:2024/06/06 10:04
Sliding Window
Time Limit: 12000MS Memory Limit: 65536KTotal Submissions: 51430 Accepted: 14767Case 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

很简单的一道题,一棵裸的线段树就可以解决,唯一要注意的就是交的时候要用C++交,不要用G++,会超时

#include <iostream>#include <stdio.h>#include <algorithm>using namespace std;#define middle int mid=(l+r)/2#define lson l,mid,i*2#define rson mid+1,r,i*2+1const int M=1000000+10;struct tree{    int l,r,minx,maxx;} tr[M<<2];void build(int l,int r,int i){    tr[i].l=l;    tr[i].r=r;    if(l==r)    {        scanf("%d",&tr[i].minx);        tr[i].maxx=tr[i].minx;        return;    }    middle;    build(lson);    build(rson);    tr[i].minx=min(tr[i*2].minx,tr[i*2+1].minx);    tr[i].maxx=max(tr[i*2].maxx,tr[i*2+1].maxx);}int minn,maxn;void get_min(int l,int r,int i){    if(l<=tr[i].l&&tr[i].r<=r)    {        minn=min(minn,tr[i].minx);        return ;    }    int mid=(tr[i].l+tr[i].r)/2;    if(r<=mid)    {        get_min(l,r,2*i);    }    else if(l>mid)    {        get_min(l,r,2*i+1);    }    else    {        get_min(lson);        get_min(rson);    }}void get_max(int l,int r,int i){    if(l<=tr[i].l&&tr[i].r<=r)    {        maxn=max(maxn,tr[i].maxx);        return ;    }    int mid=(tr[i].l+tr[i].r)/2;    if(r<=mid)    {        get_max(l,r,2*i);    }    else if(l>mid)    {        get_max(l,r,2*i+1);    }    else    {        get_max(lson);        get_max(rson);    }}int main(){    int n,k;    scanf("%d%d",&n,&k);    build(1,n,1);    for(int l=1; l<=n-k+1; l++)    {        int r=l+k-1;        minn=99999999;        get_min(l,r,1);        printf("%d",minn);        if(l!=n-k+1) printf(" ");        else printf("\n");    }    for(int l=1; l<=n-k+1; l++)    {        int r=l+k-1;        maxn=-99999999;        get_max(l,r,1);        printf("%d",maxn);        if(l!=n-k+1) printf(" ");        else printf("\n");    }    return 0;}

0 0
原创粉丝点击