单调队列。
1 /* 2823 */ 2 #include <iostream> 3 #include <sstream> 4 #include <string> 5 #include <map> 6 #include <queue> 7 #include <set> 8 #include <stack> 9 #include <vector> 10 #include <deque> 11 #include <algorithm> 12 #include <cstdio> 13 #include <cmath> 14 #include <ctime> 15 #include <cstring> 16 #include <climits> 17 #include <cctype> 18 #include <cassert> 19 #include <functional> 20 #include <iterator> 21 #include <iomanip> 22 using namespace std; 23 //#pragma comment(linker,"/STACK:102400000,1024000") 24 25 #define sti set<int> 26 #define stpii set<pair<int, int> > 27 #define mpii map<int,int> 28 #define vi vector<int> 29 #define pii pair<int,int> 30 #define vpii vector<pair<int,int> > 31 #define rep(i, a, n) for (int i=a;i<n;++i) 32 #define per(i, a, n) for (int i=n-1;i>=a;--i) 33 #define clr clear 34 #define pb push_back 35 #define mp make_pair 36 #define fir first 37 #define sec second 38 #define all(x) (x).begin(),(x).end() 39 #define SZ(x) ((int)(x).size()) 40 #define lson l, mid, rt<<1 41 #define rson mid+1, r, rt<<1|1 42 43 const int maxn = 1e6+5; 44 int n, k; 45 int a[maxn]; 46 int Q[maxn], P[maxn]; 47 int mn[maxn], mx[maxn]; 48 49 void getMin() { 50 int l = 1, r = 0; 51 int i; 52 53 for (i=0; i<k-1; ++i) { 54 while (l<=r && Q[r]>=a[i]) 55 --r; 56 Q[++r] = a[i]; 57 P[r] = i; 58 } 59 60 for (; i<n; ++i) { 61 while (l<=r && Q[r]>=a[i]) 62 --r; 63 Q[++r] = a[i]; 64 P[r] = i; 65 while (P[l] < i-k+1) 66 ++l; 67 mn[i-k+1] = Q[l]; 68 } 69 } 70 71 void getMax() { 72 int l = 1, r = 0; 73 int i; 74 75 for (i=0; i<k-1; ++i) { 76 while (l<=r && Q[r]<=a[i]) 77 --r; 78 Q[++r] = a[i]; 79 P[r] = i; 80 } 81 82 for (; i<n; ++i) { 83 while (l<=r && Q[r]<=a[i]) 84 --r; 85 Q[++r] = a[i]; 86 P[r] = i; 87 while (P[l] < i-k+1) 88 ++l; 89 mx[i-k+1] = Q[l]; 90 } 91 } 92 93 void solve() { 94 getMin(); 95 getMax(); 96 rep(i, 0, n-k+1) { 97 if (i == n-k) 98 printf("%d\n", mn[i]); 99 else 100 printf("%d ", mn[i]); 101 } 102 rep(i, 0, n-k+1) { 103 if (i == n-k) 104 printf("%d\n", mx[i]); 105 else 106 printf("%d ", mx[i]); 107 } 108 } 109 110 int main() { 111 ios::sync_with_stdio(false); 112 #ifndef ONLINE_JUDGE 113 freopen("data.in", "r", stdin); 114 freopen("data.out", "w", stdout); 115 #endif 116 117 scanf("%d %d", &n, &k); 118 rep(i, 0, n) 119 scanf("%d", &a[i]); 120 solve(); 121 122 #ifndef ONLINE_JUDGE 123 printf("time = %d.\n", (int)clock()); 124 #endif 125 126 return 0; 127 }
时间: 2024-10-13 06:03:22