Olympiad in Informatics

Monotonic Queue Study Notes

A Simple Introductory Problem

Example problem: CH1201

Given an integer sequence of length n, find a contiguous subsequence of length at most m in it, so that the sum of the whole sequence is maximized.

A solution I wrote earlier: CH1201: Maximum Subsequence Sum — Solution

First think about brute force: enumerate the endpoint and a length no greater than \(m\), mess around a bit with prefix sums and you're done. The time complexity is \(O(n^2)\), which will definitely time out. We can think about optimizing this algorithm.

Monotonic Queue

For the problem above, we can think it over: we must be ignoring some extra information; in other words, during the computation we must be throwing away some information that could be used to optimize. Let the set of possible answers be \(S\). We only want decisions that can make the answer larger, and the distance to such a decision point can't exceed \(m\), but we also don't want to lose the chance of any point being the answer. What do we do?

We can traverse the whole sequence. During the traversal, we add the possibly useful answers to \(S\), and directly discard the answers that are definitely useless. First, we can work out which answers are definitely useless:

  • Those whose distance exceeds \(m\).
  • Those with a larger prefix sum (that way the difference gets smaller, that is, the interval sum gets smaller).

Put more abstractly, suppose we have traversed up to position \(i\), and the set \(S\) contains a decision point \(j\). If either of the two holds, it is a useless answer:

  • \(j-i+1>m\)
  • \(sum[i]>sum[j]\)

In a monotonic queue, we only keep the possibly useful answers, and we always discard the useless ones. So the first condition can be guaranteed by the order of the queue, checking the head of the queue on each step of the traversal; for the second condition, we can just discard elements from the tail during the traversal. So that no answer gets thrown away in advance, we put each one into the queue. Each element enters and leaves the queue at most once, so the time complexity is \(O(n)\).

A 2D Trick

Example problem: P2216 [HAOI2007] The Ideal Square

There is an a*b matrix made up of integers. Find an n*n square region in it such that the difference between the maximum and the minimum of all the numbers in the region is minimized.

First consider a not-so-great brute force: enumerate the top-left corner \((i,j)\), then compute the range of the \(n*n\) points by brute force, for a time complexity of \(O(n^4)\).

Now optimize: first process things from the angle of the rows. Treat each point in a row as a bottom-right corner, and use two monotonic queues to get the maximum and minimum for that row; then, from the angle of the columns, find the range over a region (\(n^2\)) and update the answer. That's it.

// P2216.cpp
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <deque>
#define pr pair<int, int>
using namespace std;
const int MX_A = 1020, MX_N = 200;
int a, b, n, mat[MX_A][MX_A], maxrow[MX_A][MX_A], minrow[MX_A][MX_A], Ymx[MX_A][MX_A], Ymi[MX_A][MX_A];
int main()
{
    scanf("%d%d%d", &a, &b, &n);
    for (int i = 1; i <= a; i++)
        for (int j = 1; j <= b; j++)
            scanf("%d", &mat[i][j]);
    deque<int> dqx, dqi;
    for (int i = 1; i <= a; i++)
    {
        dqx.clear(), dqi.clear();
        dqx.push_front(1), dqi.push_back(1);
        for (int j = 2; j <= b; j++)
        {
            while (!dqx.empty() && mat[i][j] >= mat[i][dqx.back()])
                dqx.pop_back();
            while (!dqi.empty() && mat[i][j] <= mat[i][dqi.back()])
                dqi.pop_back();
            dqx.push_back(j), dqi.push_back(j);
            while (!dqx.empty() && j - dqx.front() >= n)
                dqx.pop_front();
            while (!dqi.empty() && j - dqi.front() >= n)
                dqi.pop_front();
            if (j >= n)
                maxrow[i][j - n + 1] = mat[i][dqx.front()], minrow[i][j - n + 1] = mat[i][dqi.front()];
        }
    }
    for (int i = 1; i <= b - n + 1; i++)
    {
        dqx.clear(), dqi.clear();
        dqx.push_front(1), dqi.push_back(1);
        for (int j = 2; j <= a; j++)
        {
            while (!dqx.empty() && maxrow[j][i] >= maxrow[dqx.back()][i])
                dqx.pop_back();
            while (!dqi.empty() && minrow[j][i] <= minrow[dqi.back()][i])
                dqi.pop_back();
            dqx.push_back(j), dqi.push_back(j);
            while (!dqx.empty() && j - dqx.front() >= n)
                dqx.pop_front();
            while (!dqi.empty() && j - dqi.front() >= n)
                dqi.pop_front();
            if (j >= n)
                Ymx[j - n + 1][i] = maxrow[dqx.front()][i], Ymi[j - n + 1][i] = minrow[dqi.front()][i];
        }
    }
    int ans = 2e9;
    for (int i = 1; i <= a - n + 1; i++)
        for (int j = 1; j <= b - n + 1; j++)
            ans = min(ans, Ymx[i][j] - Ymi[i][j]);
    printf("%d", ans);
    return 0;
}

Lots of 2D statistics problems can use this kind of standard trick: a moving point makes a line, a moving line makes a plane.

Practice Problems

P2219 [HAOI2007] Building the Green Belt