1 #include<iostream> 2 using namespace std; 3 const int N=1e5+10; 4 int q[N],tt; 5 int main(void){ 6 int m; 7 cin>>m; 8 for(int i=0;i<m;i++){ 9 int x; 10 cin>>x; 11 while(tt&&q[tt]>=x){//若i<j&&a[i]>=a[j],那么a[i]一点用都没有了,直接弹出 12 tt--; 13 } 14 if(tt){ 15 cout<<q[tt]<<" "; 16 }else{ 17 cout<<-1<<" "; 18 } 19 q[++tt]=x; 20 } 21 return 0; 22 }
1 #include<iostream> 2 using namespace std; 3 int n,k; 4 const int N=1e6+10; 5 int a[N],q[N]; 6 int main(void){ 7 cin>>n>>k; 8 for(int i=0;i<n;i++){ 9 cin>>a[i]; 10 } 11 //让求的是窗口内的最小值,假设当前要加入的元素为a[i],那么之前大于等于a[i]的都没用了(每次注意检查头是否还在窗口内) 12 int hh=0,tt=-1; 13 for(int i=0;i<n;i++){ 14 while(hh<=tt&&q[hh]<i-k+1) hh++;//检查是否还在窗口内 15 while(hh<=tt&&a[q[tt]]>=a[i])tt--;//弹出比当前要加入的还大的值,如果弹完了,自己就是最小的 16 q[++tt]=i; 17 if(i>=k-1){ 18 cout<<a[q[hh]]<<" "; 19 } 20 } 21 cout<<endl; 22 //求最大值的话就是反过来 23 hh=0,tt=-1; 24 for(int i=0;i<n;i++){ 25 while(hh<=tt&&q[hh]<i-k+1) hh++; 26 while(hh<=tt&&a[q[tt]]<=a[i]) tt--; 27 q[++tt]=i; 28 if(i>=k-1){ 29 cout<<a[q[hh]]<<" "; 30 } 31 } 32 return 0; 33 }