解题思路:
维护一个递增的单调队列和一个递减的单调队列,基础题。
代码:
#include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> #include <algorithm> #include <cmath> #include <vector> #include <map> #include <set> #include <queue> #include <stack> #define LL long long #define FOR(i,x,y) for(int i=x;i<=y;i++) using namespace std; const int maxn = 1000000 + 10; int N , M; int A[maxn] , Q[maxn] , ID[maxn]; int head , tail; int len1 , len2; void init() { FOR(i,1,N) scanf("%d",&A[i]); len1 = len2 = 0; } void solve_min() { head = 1 , tail = 0; for(int i=1;i<M;i++) { while(head <= tail && Q[tail] >= A[i]) tail--; tail++; Q[tail] = A[i] ; ID[tail] = i; } FOR(i,M,N) { while(head <= tail && Q[tail] >= A[i]) tail--; tail++; Q[tail] = A[i] ; ID[tail] = i; while(ID[head] <= i - M) head++; printf("%d ",Q[head]); } } void solve_max() { head = 1 , tail = 0; for(int i=1;i<M;i++) { while(head <= tail && Q[tail] <= A[i]) tail--; tail++; Q[tail] = A[i] ; ID[tail] = i; } FOR(i,M,N) { while(head <= tail && Q[tail] <= A[i]) tail--; tail++; Q[tail] = A[i] ; ID[tail] = i; while(ID[head] <= i - M) head++; printf("%d ",Q[head]); } } int main() { while(scanf("%d%d",&N,&M)!=EOF) { init(); solve_min();printf(" "); solve_max();printf(" "); } return 0; }