index > Data Structures > monotonic queue
Introduction
POJ 2823-Sliding Window , for a length of nnn array, find each lengthk (k < = n) k (k<=n)k(k<=The minimum and maximum value of the interval of n ) .
Violent for can think of an O (NK) O(NK)O ( N K ) , of course, this article is aboutO (N) O(N)O ( N ) approach.
queue
Set a deque element is {a [index], index} \{ a[index],index\}{ a[index],I n- D E X } , each taking the constraint into an array ofiiThere are several situations when there are i elements:
- The current element has a smaller value than the tail element, and the tail is continuously popped, and then the element is inserted.
- The current element is greater than the value of the tail element, then this element is inserted directly.
But there is another limitation in this question is kkk interval, then we need to check the first element of the team before each insertion, if the distance from the current subscript is greater thankkk keeps popping up the leader of the team.
So far, after the current element is processed, the head of the queue is the minimum value of the interval with the current position as the right boundary.
Reverse thinking can do the maximum.
other
Optimization space
In fact, it is easy to think that if you have an array, it is enough to save the subscript.
Another question
Except O (N) O(N)定长子区间
The maximum value of O ( N ) traversalcan actually be traversed in reverse最值区间长
.
For example, in an array, what is the maximum length of the interval whose minimum value is not less than x.
At this time, the key information we need has become a subscript, and the team's first exit condition has become a comparison with x.
The second theoretical question, the question from Niukeduo School is a similar question, but it is more complicated and the difference must be considered.
note
-
STL is
deque
still slow in actual situations, it is recommended to use an array to simulate one. -
Monotonic queues are very flexible and are often used as a step in the practice of the problem.
example
int Kase, n, m;
int a[MAXN];
int ans1[MAXN], ans2[MAXN];
deque<int> rMAX, rMIN;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = 1; i <= n; i++) {
while (!rMIN.empty() && i - rMIN.front() >= m)
rMIN.pop_front();
while (!rMAX.empty() && i - rMAX.front() >= m)
rMAX.pop_front();
while (!rMIN.empty() && a[rMIN.back()] > a[i])
rMIN.pop_back();
while (!rMAX.empty() && a[rMAX.back()] < a[i])
rMAX.pop_back();
if (rMIN.empty() || a[rMIN.back()] <= a[i])
rMIN.push_back(i);
if (rMAX.empty() || a[rMAX.back()] >= a[i])
rMAX.push_back(i);
if (i >= m) {
ans1[i] = a[rMIN.front()];
ans2[i] = a[rMAX.front()];
}
}
for (int j = m; j <= n; ++j) {
cout << ans1[j] << " \n"[j == n];
}
for (int j = m; j <= n; ++j) {
cout << ans2[j] << " \n"[j == n];
}
return 0;
}
Niuke 883F-Planting Trees Monotone Queue Double Pointer