One of the monotone queue classic problems.
Ideas
Set two monotone queues to record the maximum and minimum values, respectively. For each newly read-in number, two operations (for one of the maximum and minimum values), one is deleted if the first team is not in the sliding window, and the second is to delete the lower (or larger) value of the end of the queue and insert the current value into the tail. The minimum (large) value of each time is the team head of the current monotone queue.
"Error Point"
Be sure to write while (scanf ("%d%d", &n,&k)!=eof), otherwise it will WA.
I started with the idea of inserting the first number into the end of the queue, and then starting with the second number for subsequent operations. The problem is that if the sliding window size is 1, the first number cannot be output to the team, resulting in WA. Therefore, you must first set up an empty queue, and then insert each.
1#include <iostream>2#include <cstdio>3 using namespacestd;4 Const intmaxn=1000000+Ten;5 intN,k,maxh,minh,maxt,mint;6 intMAXQ[MAXN],MINQ[MAXN],NUM[MAXN];7 intMAXANS[MAXN],MINANS[MAXN];8 9 intMain ()Ten { One while(SCANF ("%d%d", &n,&k)! =EOF) A { - intMaxhead=0, minhead=0, maxtail=0, mintail=0; - for(intI=0; i<n;i++) the { - /*remove subscript out-of-range team first element*/ - if(Maxhead<maxtail && maxq[maxhead]<=i-k) maxhead++; - if(Minhead<mintail && minq[minhead]<=i-k) minhead++; + - + /*Delete the end of a team element*/ Ascanf"%d",&num[i]); at while(Maxhead<maxtail && num[maxq[maxtail-1]]<=num[i]) maxtail--;maxtail++; -maxq[maxtail-1]=i; - while(Minhead<mintail && num[minq[mintail-1]]>=num[i]) mintail--;mintail++; -minq[mintail-1]=i; -maxans[i]=Num[maxq[maxhead]]; -minans[i]=Num[minq[minhead]]; in } - for(inti=k-1; i<n;i++) cout<<minans[i]<<' ';cout<<Endl; to for(inti=k-1; i<n;i++) cout<<maxans[i]<<' ';cout<<Endl; + } - return 0; the}
"Monotone queue" poj2823-sliding window