Sliding Window
Time Limit: 12000MS |
|
Memory Limit: 65536K |
Total Submissions: 7213 |
|
Accepted: 1859 |
Case Time Limit: 5000MS |
Description
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 3
1 3 -1 -3 5 3 6 7
Sample Output
-1 -3 -3 -3 3 3
3 3 5 5 6 7
Source
POJ Monthly--2006.04.28, Ikki
这题让我想到了 几个月前的浙大月赛题的区间最大最小值,用队列维护的方法还是不会
用线段树AC,有点郁闷,我的半吊子线段树啊 居然10s才ac,不过幸好服务器没挂。。。。。。
代码如下
#include<stdio.h>
#include<string.h>
#define MAX 1001010
struct node{
int l,r;
int m;
};
node Max_Stree[2*MAX];
node Min_Stree[2*MAX];
int w[MAX];
int getmax(int a,int b)
{
return a>b?a:b;
}
int getmin(int a,int b)
{
return a>b?b:a;
}
int Build_Max(int now,int l,int r){
Max_Stree[now].l=l;
Max_Stree[now].r=r;
if(l==r)Max_Stree[now].m=w[l];
else {
int mid=(l+r)>>1;
int max1=Build_Max(2*now,l,mid);
int max2=Build_Max(2*now+1,mid+1,r);
Max_Stree[now].m=getmax(max1,max2);
}
return Max_Stree[now].m;
}
int Build_Min(int now,int l,int r){
Min_Stree[now].l=l;
Min_Stree[now].r=r;
if(l==r)Min_Stree[now].m=w[l];
else {
int mid=(l+r)>>1;
int min1=Build_Min(2*now,l,mid);
int min2=Build_Min(2*now+1,mid+1,r);
Min_Stree[now].m=getmin(min1,min2);
}
return Min_Stree[now].m;
}
int Find_Max(int now,int l,int r){
int left=Max_Stree[now].l;
int right=Max_Stree[now].r;
if(left==l&&right==r)
return Max_Stree[now].m;
int mid=(left+right)>>1;
if(mid+1>r)return Find_Max(2*now,l,r);
if(mid<l)return Find_Max(2*now+1,l,r);
else return getmax(Find_Max(2*now,l,mid),Find_Max(2*now+1,mid+1,r));
}
int Find_Min(int now,int l,int r){
int left=Min_Stree[now].l;
int right=Min_Stree[now].r;
if(left==l&&right==r)
return Min_Stree[now].m;
int mid=(left+right)>>1;
if(mid+1>r)return Find_Min(2*now,l,r);
if(mid<l)return Find_Min(2*now+1,l,r);
else return getmin(Find_Min(2*now,l,mid),Find_Min(2*now+1,mid+1,r));
}
posted on 2009-02-19 11:16
KNIGHT 阅读(330)
评论(0) 编辑 收藏 引用