Sliding Window
Time Limit: 12000MS | Memory Limit: 65536K | |
Total Submissions: 51430 | Accepted: 14767 | |
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.
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 33 3 5 5 6 7
很简单的一道题,一棵裸的线段树就可以解决,唯一要注意的就是交的时候要用C++交,不要用G++,会超时
#include <iostream> #include <stdio.h> #include <algorithm> using namespace std; #define middle int mid=(l+r)/2 #define lson l,mid,i*2 #define rson mid+1,r,i*2+1 const int M=1000000+10; struct tree { int l,r,minx,maxx; } tr[M<<2]; void build(int l,int r,int i) { tr[i].l=l; tr[i].r=r; if(l==r) { scanf("%d",&tr[i].minx); tr[i].maxx=tr[i].minx; return; } middle; build(lson); build(rson); tr[i].minx=min(tr[i*2].minx,tr[i*2+1].minx); tr[i].maxx=max(tr[i*2].maxx,tr[i*2+1].maxx); } int minn,maxn; void get_min(int l,int r,int i) { if(l<=tr[i].l&&tr[i].r<=r) { minn=min(minn,tr[i].minx); return ; } int mid=(tr[i].l+tr[i].r)/2; if(r<=mid) { get_min(l,r,2*i); } else if(l>mid) { get_min(l,r,2*i+1); } else { get_min(lson); get_min(rson); } } void get_max(int l,int r,int i) { if(l<=tr[i].l&&tr[i].r<=r) { maxn=max(maxn,tr[i].maxx); return ; } int mid=(tr[i].l+tr[i].r)/2; if(r<=mid) { get_max(l,r,2*i); } else if(l>mid) { get_max(l,r,2*i+1); } else { get_max(lson); get_max(rson); } } int main() { int n,k; scanf("%d%d",&n,&k); build(1,n,1); for(int l=1; l<=n-k+1; l++) { int r=l+k-1; minn=99999999; get_min(l,r,1); printf("%d",minn); if(l!=n-k+1) printf(" "); else printf("\n"); } for(int l=1; l<=n-k+1; l++) { int r=l+k-1; maxn=-99999999; get_max(l,r,1); printf("%d",maxn); if(l!=n-k+1) printf(" "); else printf("\n"); } return 0; }