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.
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
这题可以用单调队列搞 见我这篇
poj2823Sliding Window【单调队列经典题】
长记性记得g++超时
/***********
poj Sliding Window
2016.3.17
***********/
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct Node
{
int l,r,minn,maxn;
}num[4000000];
int cnt[1000000];
int min(int a,int b){if(a<b)return a;return b;}
int max(int a,int b){if(a>b)return a;return b;}
void build(int rt,int l,int r)
{
num[rt].l=l;num[rt].r=r;
if(l==r)
{
num[rt].maxn=cnt[l];
num[rt].minn=cnt[l];
return;
}
int mid=(l+r)/2;
build(rt<<1,l,mid);
build(rt<<1|1,mid+1,r);
num[rt].maxn=max(num[rt<<1].maxn,num[rt<<1|1].maxn);
num[rt].minn=min(num[rt<<1].minn,num[rt<<1|1].minn);
}
int query1(int rt,int l,int r)
{
if(num[rt].l==l&&num[rt].r==r)
return num[rt].minn;
int mid=(num[rt].l+num[rt].r)/2;
if(r<=mid) return query1(rt<<1,l,r);
else if(l>mid) return query1(rt<<1|1,l,r);
else
return min(query1(rt<<1,l,mid),query1(rt<<1|1,mid+1,r));
}
int query2(int rt,int l,int r)
{
if(num[rt].l==l&&num[rt].r==r)
return num[rt].maxn;
int mid=(num[rt].l+num[rt].r)/2;
if(r<=mid) return query2(rt<<1,l,r);
else if(l>mid) return query2(rt<<1|1,l,r);
else
return max(query2(rt<<1,l,mid),query2(rt<<1|1,mid+1,r));
}
int main()
{
// freopen("cin.txt","r",stdin);
int n,k;
while(~scanf("%d%d",&n,&k))
{
for(int i=1;i<=n;i++)scanf("%d",&cnt[i]);
build(1,1,n);
for(int i=1;i<=n-k;i++)
printf("%d ",query1(1,i,i+k-1));
printf("%d\n",query1(1,n-k+1,n));
for(int i=1;i<=n-k;i++)
printf("%d ",query2(1,i,i+k-1));
printf("%d\n",query2(1,n-k+1,n));
}
return 0;
}