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 31 3 -1 -3 5 3 6 7
Sample Output
-1 -3 -3 -3 3 33 3 5 5 6 7
线段树水题,但这道题拿线段树是卡过的,拿G++提交就会超时,所以必须用C++提交。
#include#include #include #include using namespace std;const int MAXN = 1000005;int datain[MAXN];//下标从1开始,边的编号。int Min[MAXN*2],Max[MAXN*2];//线段树的结点编号从0开始。int lnext[MAXN*2],rnext[MAXN*2];int l[MAXN*2],r[MAXN*2];int tot;int buildTree(int ll,int rr){ int cur=tot++; l[cur]=ll; r[cur]=rr; if(ll==rr) { Min[cur] = Max[cur] = datain[ll]; //printf("%d**\n",seg[cur]); lnext[cur]=rnext[cur]=-1; return cur; } int mid=(ll+rr)>>1; lnext[cur]=buildTree(ll,mid); rnext[cur]=buildTree(mid+1,rr); Min[cur]=min(Min[lnext[cur]],Min[rnext[cur]]); Max[cur]=max(Max[lnext[cur]],Max[rnext[cur]]); return cur;}int qmin(int ll,int rr,int cur){ //printf("%d %d %d\n",cur,l[cur],r[cur]); if(l[cur]==ll&&r[cur]==rr) return Min[cur]; int mid=(l[cur]+r[cur])/2; if(ll>=mid+1) return qmin(ll,rr,rnext[cur]); else if(rr =mid+1) return qmax(ll,rr,rnext[cur]); else if(rr n) k=n; for(int i=1; i<=n; i++) { scanf("%d",&datain[i]); } int Min,Max; buildTree(1,n); for(int i=1; i<=n-k+1; i++) printf("%d ",qmin(i,i+k-1,0)); puts(""); for(int i=1; i<=n-k+1; i++) printf("%d ",qmax(i,i+k-1,0)); puts(""); }}