Description
An array of size n ≤ 106is given to you. There is a sliding window of size k which is movingfrom the very left of the array to the very right. You can only see the knumbers in the window. Each time the sliding window moves rightwards by oneposition. Following is an example:
The array is [1 3 -1 -3 5 3 6 7], and k is 3.
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 minimumvalues in the sliding window at each position.
Input
The input consists of twolines. The first line contains two integers n and k which are thelengths of the array and the sliding window. There are n integers in thesecond line.
Output
There are two lines in theoutput. The first line gives the minimum values in the window at each position,from left to right, respectively. The second line gives the maximum values.
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
题目简介:给定一组含有n个数的数组,以及一个窗口长度k。找到每个窗口长度中的最大数和最小数。
方法:双端队列。将每个数的数组下标存入队列。找最大数时,按降序排列。队头对应数即为窗口长度中最大数。当对头+k-1小于此时处理数据的数组下标,即超过窗口长度,删去对头元素。最小数同理。
#include<iostream> #include<deque> using namespace std; int num[1000010], max1[1000010], min1[1000010]; int main() { int n, k, i; while(scanf("%d%d",&n, &k)!=EOF) { for(i = 0;i<n;i++) { scanf("%d",&num[i]); } deque<int> q1, q2; q1.clear(); q2.clear(); for(i = 0;i<n;i++) { while(!q1.empty()&&num[i]>num[q1.back()]) { q1.pop_back(); } while(!q1.empty()&&i - k + 1>q1.front()) { q1.pop_front(); } q1.push_back(i); max1[i] = num[q1.front()]; while(!q2.empty()&&num[i]<num[q2.back()]) { q2.pop_back(); } while(!q2.empty()&&i - k + 1>q2.front()) { q2.pop_front(); } q2.push_back(i); min1[i] = num[q2.front()]; } for(i = k - 1;i<n - 1;i++) { printf("%d ",min1[i]); } printf("%d\n",min1[i]); for(i = k - 1;i< n - 1;i++) { printf("%d ",max1[i]); } printf("%d\n",max1[i]); } system("pause"); return 0; }