Olympiad in Informatics

Optimizing Dynamic Programming with a Monotonic Queue

Introduction

Sometimes, when we're working through problems day to day, we run into nasty DP problems like these. They generally have the following traits:

  • Multi-dimensional dynamic programming
  • Many nested loops, so they can't get AC on the extreme-case data.
  • They usually show up in interval DP, and the brute-force algorithm's complexity is generally \(O(n^3)\).

At this point we can use a monotonic queue to optimize, and the time complexity can be further reduced to \(O(n^2)\) or \(O(nm)\). If any of you don't know monotonic queues, you can go learn them, and while you're at it you can take a look at this post: CH1201: Maximum Subsequence Sum — Solution

Overall on this optimization technique

Let's look at an example problem: Fence - POJ. This problem is a fairly simple classic DP. Define the state \(dp[i][j]\) to mean that the first \(i\) people have taken care of the first \(j\) units of the wall. Write out the equation:

\[dp[i][j] = min_{S_i - l_i \leq k < S_i}\{dp[i-1][k]+profit_i*(j-k)\}\]

This way, the complexity of the whole algorithm is \(O(n^3)\). Can we bring it down to \(O(n^2)\)? We can rearrange the whole equation a bit, and afterwards it looks like this:

\[dp[i][j] = min_{S_i - l_i \leq k < S_i}\{dp[i-1][k]-profit_i*k\}+profit_i*j\]

We notice that this way, under the loop over \(i\), the whole equation is more or less only tied up with the variable \(k\). We find that as long as \(k_1<k_2\) and \(dp[i-1][k_1]-profit_i*k_1<dp[i-1][k_2]-profit_i*k_2\), we can directly rule out the answer \(k_1\). So we can use a monotonic queue to do exactly that.

Below is the core DP code:

int calc(int i, int k)
{
    return dp[i - 1][k] - wks[i].p * k;
}

// in ( int main() )
for (int i = 1; i <= k; i++)
{
    deque<int> q;
    for (int j = max(0, wks[i].s - wks[i].l); j <= wks[i].s - 1; j++)
    {
        while (!q.empty() && calc(i, q.back()) <= calc(i, j))
            q.pop_back();
        q.push_back(j);
    }
    for (int j = 1; j <= n; j++)
    {
        dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
        if (j >= wks[i].s)
        {
            while (!q.empty() && q.front() < j - wks[i].l)
                q.pop_front();
            if (!q.empty())
                dp[i][j] = max(dp[i][j], calc(i, q.front()) + wks[i].p * j);
        }
    }
}

In Conclusion

This whole monotonic queue optimization lays the groundwork for the slope optimization later on (because the reason I learned this monotonic queue optimization was that a problem required slope optimization), so please make sure you really get this technique.