標籤:替換 while lines eterm move max 題意 直接 spec
An array of size
n ≤ 10 6 is given to you. There is a sliding window of size
kwhich is moving from the very left of the array to the very right. You can only see the
k numbers in the window. Each time the sliding window moves rightwards by one position. 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 minimum values in the sliding window at each position.
Input
The input consists of two lines. The first line contains two integers
n and
k which are the lengths of the array and the sliding window. There are
n integers in the second line.
Output
There are two lines in the output. 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 31 3 -1 -3 5 3 6 7
Sample Output
-1 -3 -3 -3 3 33 3 5 5 6 7
題意:給出n個數和區間長度m,然後求每個長度為m的區間的最大值和最小值
思路:因為題目所給的範圍比較大,nlogn演算法其實也可以,因為只有一組資料,但是我們把他作為滑動視窗的入門題來進行解析,滑動視窗是一個求一個區間的的值,區間長度固定的一個o(n)演算法
下面首先我們熟悉下雙端隊列
標頭檔 #include<deque>
定義 deque<int> q;
頭部插入 q.push_front()
頭部刪除 q.pop_front()
尾部插入 q.push_back()
尾部刪除 q.pop_back()
取頭值 q.front()
取尾值 q.back()
滑動視窗是一個維護一個隊列,裡面存的是最大值下表
最前的那個是當前區間最大值
給出一個例子
5 6 4 9 1
我們區間長度為2
開始5進入隊列,然後因為6比5大,5就被踢出隊列,6進來,因為隊列最前面的就是區間裡的最大值
然後4也到6得後面,因為如果6出去了,4就是當前得最大值了
後面9比4和6都大,就可以替換掉前面得數
主要思想:按順序儲存一個單調遞減得序列,比他大得直接更新,小的後面區間用的到得一種思想,然後判斷下標是否出區間就可以,每個數都最多進隊列一次,出隊列一次
然後這個提我們用兩個雙端隊列 一個維護最大值,一個最小值即可
#include<cstdio>#include<cstring>#include<cmath>#include<iostream>#include<deque>#include<vector>#include<algorithm>using namespace std;int n,m;int a[1000001];int b[1000001];int c[1000001];deque<int> qx,qn;int cnt;int main(){ while(scanf("%d%d",&n,&m)!=EOF) { while(!qx.empty()) qx.pop_front(); while(!qn.empty()) qn.pop_front(); for(int i=0;i<n;i++) scanf("%d",&a[i]); for(int i=0;i<n;i++) { while(!qx.empty()&&a[i]>=a[qx.back()])//判斷是否新加得數比前面得大,大的話我們就要把最大值放最前, qx.pop_back(); qx.push_back(i); while(!qn.empty()&&a[i]<=a[qn.back()]) qn.pop_back(); qn.push_back(i); if(i>=m-1) { while(!qx.empty()&&qx.front()<=i-m) qx.pop_front();//我們把出了區間的數踢出隊列 b[cnt]=a[qx.front()]; while(!qn.empty()&&qn.front()<=i-m) qn.pop_front(); c[cnt++]=a[qn.front()]; } } for(int i=0;i<cnt;i++) { if(i==0) printf("%d",c[i]); else printf(" %d",c[i]); } printf("\n"); for(int i=0;i<cnt;i++) { if(i==0) printf("%d",b[i]); else printf(" %d",b[i]); } printf("\n"); }}
POJ - 2823 Sliding Window (滑動視窗入門)