"Monotonous queue" queue monotone board

Monotonous queue learning premise Know

Monotone queue for a general class of optimization, such dp optimization, a series of questions, or in half, compared to the same type of queue monotone monotonic stack, the broader scope, the scope is broader test. Is a monotone queue length \ (n-\) the number of columns, find continuous \ (m \) number, maximum and minimum values determined quickly

Algorithms content

Competition need to use Hu points

1 is determined, generally monotonically queue for optimizing the answer 1-2 minutes

2, for a wide range monotonous queue, the proposed focus on practice

Monotone queue seeking the maximum and minimum interval slightly speaking

Monotone queue structure that is similar to the deque which satisfies the tail into the scratch, the scratch is also satisfied deque may also be from the end of the form, so that the number into the queue has two values, a first values ​​are values ​​into the number itself, the second value is a number of incoming time indicates how long the entry, then it must be satisfied that, when the current value of the number of larger (smaller) in the queue from the queue tail starting the number, then you can directly to the number of the tail kicked, until the queue is empty or queue several greater than (less than) until the current number, or the head of the queue in the queue at the time have been considered outside the region, then we The first team will pop up. By this thinking, the code seems to be out

For example, we seek the minimum range, then we can get the following code

int front = 1, back = 0;
    for (int i = 1; i <= n; i++) { 
        if(q[front].idx + m < i) front++; //判断队首是否越界
        while(front <= back && q[back].x >= arr[i]) back--; //查看进入的数是否小于队尾的数
        back++; q[back].idx = i - 1, q[back].x = arr[i];
        if(i >= m) printf("%d ", q[front].x);
    } puts("");

This is the entire code of our monotonous queue, the following codes refer sliding window

//#define fre yes

#include <cstdio>

int n, m;

const int N = 1000005;
struct Node {
    int idx, x;
} q[N];
int arr[N];

int main() {
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= n; i++) {
        scanf("%d", &arr[i]);
    }
    
    int front = 1, back = 0;
    for (int i = 1; i <= n; i++) {
        if(q[front].idx + m < i) front++;
        while(front <= back && q[back].x >= arr[i]) back--;
        back++; q[back].idx = i - 1, q[back].x = arr[i];
        if(i >= m) printf("%d ", q[front].x);
    } puts("");
    
    front = 1, back = 0;
    for (int i = 1; i <= n; i++) {
        if(q[front].idx + m < i) front++;
        while(front <= back && q[back].x <= arr[i]) back--;
        back++; q[back].idx = i - 1, q[back].x = arr[i];
        if(i >= m) printf("%d ", q[front].x);
    } return 0;
}

Guess you like

Origin www.cnblogs.com/Nicoppa/p/11545302.html