经典题
单调队列
Codes:
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #include<algorithm> 5 6 using namespace std; 7 const int N = 1000000 + 5; 8 9 int cnt1,cnt2,n,k,a[N],cn; 10 int q1[N],q2[N],minn[N],maxx[N]; 11 int ans1[N],ans2[N]; 12 int main(){ 13 scanf("%d%d",&n,&k); 14 int head1,tail1,head2,tail2; 15 head1 = tail1 = head2 = tail2 = 0; 16 for(int i = 1;i <= n;++ i){ 17 scanf("%d",&a[i]); 18 while(head1 <= tail1 && a[i] < a[q1[tail1]]) { 19 tail1 --; 20 } 21 22 q1[++ tail1] = i; 23 24 while(q1[head1] < i - k + 1) 25 head1 ++; 26 if(i >= k) 27 minn[++ cn] = q1[head1]; 28 while(head2 <= tail2 && a[i] > a[q2[tail2]]) 29 tail2 --; 30 q2[++ tail2] = i; 31 while(q2[head2] < i - k + 1) 32 head2 ++; 33 if(i >= k) 34 maxx[cn] = q2[head2]; 35 } 36 for(int i = 1;i <= cn;++ i) 37 if(i == n) 38 cout << a[minn[i]]; 39 else 40 cout << a[minn[i]] << " "; 41 cout << ' '; 42 for(int i = 1;i <= cn;++ i) 43 if(i == n) 44 cout << a[maxx[i]]; 45 else 46 cout << a[maxx[i]] << " "; 47 return 0; 48 }