题目:
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
题意:给长度为n的序列和k,求每个位置开始连续k个数字的最大值和最小值
思路:区间求最值,第一反应就是线段树,然后发现poj神奇的评测系统,提交g++会tle,c++就可以过了。
线段树模板题
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#define INF 0x3f3f3f3f
#define mod 1000000007
#define pi acos(-1)
using namespace std;
struct node
{
int maxx,minn;
}ans[1000020];
int n,k,MAX[1000020*4],MIN[1000020*4],ansmax,ansmin;
void build(int t,int l,int r)
{
if (l==r)
{
scanf("%d",&MAX[t]);
MIN[t]=MAX[t];
}
else
{
int mid=(l+r)>>1;
build(t<<1,l,(l+r)>>1);
build(t<<1|1,mid+1,r);
MAX[t]=max(MAX[t<<1],MAX[t<<1|1]);
MIN[t]=min(MIN[t<<1],MIN[t<<1|1]);
}
}
void search(int t,int l,int r,int L,int R)
{
if (l>R || r<L) return;
if(L<=l && r<=R)
{
ansmax=max(ansmax,MAX[t]);
ansmin=min(ansmin,MIN[t]);
}
else
{
int mid=(l+r)>>1;
if (L<=mid)
search(t<<1,l,mid,L,R);
if (R>mid)
search(t<<1|1,mid+1,r,L,R);
}
}
int main()
{
cin>>n>>k;
build(1,1,n);
for (int i=1;i<=n-k+1;i++)
{
ansmax=-INF;
ansmin=INF;
search(1,1,n,i,i+k-1);
ans[i].maxx=ansmax,ans[i].minn=ansmin;
}
for (int i=1;i<=n-k+1;i++)
printf("%d ",ans[i].minn);
printf("\n");
for (int i=1;i<=n-k+1;i++)
printf("%d ",ans[i].maxx);
return 0;
}