佇列_單調佇列_POJ2823_Sliding Window
阿新 • • 發佈:2018-12-19
思路分析:
設輸入序列為, 從左向右依次掃描輸入序列, 並維持兩個佇列minde和maxde, 當考察時, 其中佇列minde和maxde中至多含有k個元素, minde中元素嚴格單調遞增, maxde中元素嚴格單調遞減, 具體如下AC程式碼, 由於輸入序列中每個元素至多入佇列一次和出佇列一次, 因此下面程式的時間複雜度為O(n)
//POJ2823_Sliding Window #include <iostream> #include <cstdio> #include <deque> #include <algorithm> using namespace std; const int MAX = 1e6 + 5; int arr[MAX], n, k, minval[MAX], maxval[MAX]; deque<int> minde, maxde; int main(){ scanf("%d %d", &n, &k); for(int i = 1; i <= n; ++i) scanf("%d", &arr[i]); minval[1] = maxval[1] = arr[1], minde.push_back(1), maxde.push_back(1); for(int i = 2; i <= n; ++i){ if(minde[0] < i - k + 1) minde.pop_front(); if(maxde[0] < i - k + 1) maxde.pop_front(); while(!minde.empty() && arr[minde.back()] >= arr[i]) minde.pop_back(); minde.push_back(i), minval[i] = arr[minde[0]]; while(!maxde.empty() && arr[maxde.back()] <= arr[i]) maxde.pop_back(); maxde.push_back(i), maxval[i] = arr[maxde[0]]; } for(int i = k; i <= n; ++i) cout << minval[i] << " "; cout << endl; for(int i = k; i <= n; ++i) cout << maxval[i] << " "; cout << endl; return 0; }