Topic description
Now there is a bunch of numbers with a total of N numbers (N<=10^6), and a window of size k. Now this slides from the left to the right, slides one unit at a time, and finds the maximum and minimum values in the window after each slide.
E.g:
The array is [1 3 -1 -3 5 3 6 7], and k = 3.
Input and output format
Input format:There are two lines in the input, the first line is n, k.
The second line is n numbers (<INT_MAX).
Output format:There are two lines of output, the first line is the minimum value of each window sliding
The second line is the maximum value of each window sliding
Input and output example
8 3
1 3 -1 -3 5 3 6 7
-1 -3 -3 -3 3 3
3 3 5 5 6 7
illustrate
50% of the data, n<=10^5
100% data, n<=10^6
Solution:
This question is a template question for monotonic queues. . .
However, although the idea of monotonic queue is simple, it is easy to make mistakes in various judgments of the code, so a line segment tree water is divided into waves.
The idea is that the interval query is the most valuable, and it is OK to maintain it.
Code:
1 #include<bits/stdc++.h> 2 #define il inline 3 #define lson l,m,rt<<1 4 #define rson m+1,r,rt<<1|1 5 const int inf=2147483647,N=1e6+7; 6 using namespace std; 7 int n,k,cnt,ans1[N],ans2[N]; 8 struct node{ 9 int maxn,minn; 10 }tr[N<<2]; 11 il int gi(){ 12 int a=0;char x=getchar();bool f=0; 13 while((x<'0'||x>'9')&&x!='-')x=getchar(); 14 if(x=='-')x=getchar(),f=1; 15 while(x>='0'&&x<='9')a=a*10+x-48,x=getchar(); 16 return f?-a:a; 17 } 18 il int Max ( int a, int b) { return a> b? a: b;} 19 il int Min ( int a, int b) { return a> b? b: a;} 20 il void pushup ( int rt) { 21 tr [rt] .maxn = Max (tr [rt << 1 ] .maxn, tr [rt << 1 | 1 ] .maxn); 22 tr [rt] .minn = Min (tr [rt << 1 ] .minn, tr [rt << 1 | 1 ] .minn); 23 } 24 il void build(int l,int r,int rt){ 25 if(l==r){tr[rt].maxn=tr[rt].minn=gi();return;} 26 int m=l+r>>1; 27 build(lson),build(rson); 28 pushup(rt); 29 } 30 il void query(int L,int R,int l,int r,int rt,int cnt){ 31 if(L<=l&&R>=r){ans1[cnt]=Min(ans1[cnt],tr[rt].minn);ans2[cnt]=Max(ans2[cnt],tr[rt].maxn);return;} 32 int m=l+r>>1; 33 if(L<=m)query(L,R,lson,cnt); 34 if(R>m)query(L,R,rson,cnt); 35 } 36 int main(){ 37 n=gi(),k=gi()-1; 38 for(int i=1;i<=n;i++)ans1[i]=inf,ans2[i]=-inf; 39 build(1,n,1); 40 for(int i=1;i+k<=n;i++)query(i,i+k,1,n,1,++cnt); 41 for(int i=1;i<=cnt;i++)printf("%d ",ans1[i]); 42 printf("\n"); 43 for(int i=1;i<=cnt;i++)printf("%d ",ans2[i]); 44 return 0; 45 }