Time Limit: 12000MS | Memory Limit: 65536K | |
Total Submissions: 14472 | Accepted: 4071 | |
Case Time Limit: 5000MS |
Description
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
Output
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
#include<cstdio>
#include<cstring>
#define LL(x) (x<<1)
#define RR(x) (x<<1|1)
#define min(a,b) a>b?b:a
#define max(a,b) a>b?a:b
int a[1000010];
int rrmin[1000010],rrmax[1000010];
struct TREE
{
int left,right;
int rmin,rmax;
int mid() { return ((left+right)>>1); }
}tree[1000010*3];
void build(int left,int right,int idx)
{
tree[idx].left=left;
tree[idx].right=right;
if(tree[idx].left==tree[idx].right)
{
tree[idx].rmax=tree[idx].rmin=a[left];
return ;
}
int mid=tree[idx].mid();
build(left,mid,LL(idx));
build(mid+1,right,RR(idx));
tree[idx].rmin=min(tree[LL(idx)].rmin,tree[RR(idx)].rmin);
tree[idx].rmax=max(tree[LL(idx)].rmax,tree[RR(idx)].rmax);
}
int lmin,lmax;
void query(int left,int right,int idx)
{
if(left<=tree[idx].left&&tree[idx].right<=right)
{
lmin=min(lmin,tree[idx].rmin);
lmax=max(lmax,tree[idx].rmax);
return ;
}
int mid=tree[idx].mid();
if(right<=mid) query(left,right,LL(idx));
else if(left>mid) query(left,right,RR(idx));
else
{
query(left,mid,LL(idx));
query(mid+1,right,RR(idx));
}
}
int main()
{
int n,k;
scanf("%d%d",&n,&k);
k--;
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
build(1,n,1);
for(int i=1;i+k<=n;i++)
{
lmin=1<<30-1;
lmax=-1<<30;
query(i,i+k,1);
rrmin[i]=lmin;
rrmax[i]=lmax;
}
for(int i=1;i+k<=n;i++)
if(i!=1)printf(" %d",rrmin[i]);
else printf("%d",rrmin[i]);
printf("/n");
for(int i=1;i+k<=n;i++)
if(i!=1) printf(" %d",rrmax[i]);
else printf("%d",rrmax[i]);
printf("/n");
return 0;
}