Olympiad in Informatics

BZOJ4709: [JSOI2011] Lemon — Solution

Main Idea

First, notice that the two ends don't matter, so we can directly do a linear DP over segments. Thinking about the brute force the normal way, we find that we have to enumerate the color every time, which is a big hassle. But we can find an especially nice property: the color of each segment is determined by the last element of that segment, because, as we realize, when some other color is chosen, we could perfectly well adjust this segment's right endpoint so that the next segment is no worse.

Knowing this, the DP is \(\Theta(n^2)\), so let's consider optimizing it further. Expand this DP formula:

\[ f_{j - 1} + a_i(pre_j - 1)^2 = (2a_i pre_i)(pre_j - 1) + f_i - a_i pre_i^2 \]

Of course, this is the DP formula already put into line form. Set the variables \(x = (pre_j - 1), k = (2a_i pre_i), b = f_i - a_i pre_i^2, y = f_{j - 1} + a_i(pre_j - 1)^2\). We notice a squared term in the original formula, and it grows faster than \(y = x\), so there is decision monotonicity, and all we need is a monotonic stack. Before adding an element, we need to find the decision boundary between the last two decisions, then check whether that decision boundary is greater than the new decision boundary; if it is, pop it (because the former won't be better).

Code

// BZ4709.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 1e5 + 200;

typedef long long ll;

int n, ai[MAX_N], idx[MAX_N], cnt[MAX_N];
ll dp[MAX_N];
deque<int> stk[MAX_N];

ll calc(int x, ll y) { return dp[x - 1] + 1LL * ai[x] * y * y; }

int check(int x, int y)
{
    int l = 1, r = n, res = n + 1;
    while (l <= r)
    {
        int mid = (l + r) >> 1;
        if (calc(x, mid - idx[x] + 1) >= calc(y, mid - idx[y] + 1))
            r = mid - 1, res = mid;
        else
            l = mid + 1;
    }
    return res;
}

int main()
{
    scanf("%d", &n);
    for (int i = 1, x; i <= n; i++)
    {
        scanf("%d", &ai[i]), x = ai[i];
        idx[i] = ++cnt[ai[i]];
        while (stk[x].size() >= 2 && check(stk[x][stk[x].size() - 2], stk[x].back()) <= check(stk[x].back(), i))
            stk[x].pop_back();
        stk[x].push_back(i);
        while (stk[x].size() >= 2 && check(stk[x][stk[x].size() - 2], stk[x].back()) <= idx[i])
            stk[x].pop_back();
        dp[i] = calc(stk[x].back(), idx[i] - idx[stk[x].back()] + 1);
    }
    printf("%lld\n", dp[n]);
    return 0;
}