@Chilling
2017-02-16T17:57:49.000000Z
字数 2054
阅读 1356
线段树
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
题意:给出n个数,求连续的k个数字中的最大值和最小值。区间内最大值和最小值的查询,n比较大,超过了,用RMQ做的话超内存了…
#include<stdio.h>
#include<algorithm>
using namespace std;
int a[1000005];
struct node
{
int l,r,maxs,mins;
}s[4*1000005];
void build(int id,int l,int r)
{
s[id].l=l;
s[id].r=r;
if(l==r)
s[id].maxs=s[id].mins=a[l];
else
{
int mid=(l+r)/2;
build(id*2,l,mid);
build(id*2+1,mid+1,r);
s[id].maxs=max(s[id*2].maxs,s[id*2+1].maxs);
s[id].mins=min(s[id*2].mins,s[id*2+1].mins);
}
}
int big(int id,int l,int r)
{
if(l<=s[id].l&&s[id].r<=r)
return s[id].maxs;
int mid=(s[id].l+s[id].r)/2;
if(r<=mid)
return big(id*2,l,r);
else if(l>mid)
return big(id*2+1,l,r);
else
return max(big(id*2,l,r),big(id*2+1,l,r));
}
int small(int id,int l,int r)
{
if(l<=s[id].l&&s[id].r<=r)
return s[id].mins;
int mid=(s[id].l+s[id].r)/2;
if(r<=mid)
return small(id*2,l,r);
else if(l>mid)
return small(id*2+1,l,r);
else
return min(small(id*2,l,r),small(id*2+1,l,r));
}
int main()
{
int n,k;
while(scanf("%d%d",&n,&k)!=EOF)
{
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
build(1,1,n);
for(int st=1;st<=n-k+1;st++)
{
int en=st+k-1;
if(st==1)
printf("%d",small(1,st,en));
else
printf(" %d",small(1,st,en));
}
printf("\n");
for(int st=1;st<=n-k+1;st++)
{
int en=st+k-1;
if(st==1)
printf("%d",big(1,st,en));
else
printf(" %d",big(1,st,en));
}
printf("\n");
}
return 0;
}