标签:
题目链接:http://poj.org/problem?id=2823
Description
Window position | Minimum value | Maximum value |
---|---|---|
[1 3 -1] -3 5 3 6 7 | -1 | 3 |
1 [3 -1 -3] 5 3 6 7 | -3 | 3 |
1 3 [-1 -3 5] 3 6 7 | -3 | 5 |
1 3 -1 [-3 5 3] 6 7 | -3 | 5 |
1 3 -1 -3 [5 3 6] 7 | 3 | 6 |
1 3 -1 -3 5 [3 6 7] | 3 | 7 |
Your task is to determine the maximum and minimum values in the sliding window at each position.
Input
Output
Sample Input
8 3 1 3 -1 -3 5 3 6 7
Sample Output
-1 -3 -3 -3 3 3 3 3 5 5 6 7
Source
1 #include <iostream> 2 #include <queue> 3 #include <cstdio> 4 #include <cstring> 5 6 using namespace std; 7 8 const int maxn = 1000010; 9 int n, k; 10 int num[maxn]; 11 int mmin[maxn]; 12 int mmax[maxn]; 13 typedef struct bigg { 14 bool operator()(const int a, const int b) { 15 return num[a] < num[b]; 16 } 17 }bigg; 18 19 typedef struct smal { 20 bool operator()(const int a, const int b) { 21 return num[a] > num[b]; 22 } 23 }smal; 24 25 priority_queue<int, vector<int>, bigg> upstream; 26 priority_queue<int, vector<int>, smal> downstream; 27 int cntu, cntd; 28 int main() { 29 scanf("%d %d", &n, &k); 30 if(k > n) { 31 k = n; 32 } 33 cntu = 0; 34 cntd = 0; 35 for(int i = 1; i <= n; i++) { 36 scanf("%d", &num[i]); 37 } 38 for(int i = 1; i <= k; i++) { 39 upstream.push(i); 40 downstream.push(i); 41 } 42 mmin[cntd++] = num[downstream.top()]; 43 mmax[cntu++] = num[upstream.top()]; 44 for(int i = k + 1; i <= n; i++) { 45 upstream.push(i); 46 downstream.push(i); 47 while(i - downstream.top() >= k) { 48 downstream.pop(); 49 } 50 mmin[cntd++] = num[downstream.top()]; 51 while(i - upstream.top() >= k) { 52 upstream.pop(); 53 } 54 mmax[cntu++] = num[upstream.top()]; 55 } 56 for(int i = 0; i < cntd; i++) { 57 cout << mmin[i] << " "; 58 } 59 cout << endl; 60 for(int i = 0; i < cntu; i++) { 61 cout << mmax[i] << " "; 62 } 63 cout << endl; 64 }
标签:
原文地址:http://www.cnblogs.com/vincentX/p/4769233.html