题解:P11598 [NOISG 2018 Finals] Safety

· · 题解

前言

这是一道带转移限制的 slope trick 模板题。

思路

首先,本题最朴素的 dp 转移方程不难想,设 f_{i, j} 表示处理完前 i 个数,第 i 个数设置为 j 的最小值,有转移:

f_{i, j} \leftarrow \min_{|k - j| \le h} f_{i - 1, k} + |a_i - j|

我们发现这个转移式的值只与前半部分有关,后半部分为定值。对于绝对值函数,我们自然可以联想到凸性,所以我们可以考虑将转移式子刻画在图像上,我们可以归纳的证明因为初始时 f_{1, *} 就等于一个绝对值函数,它是凸的,所以取 \min 以及 + 后依旧拥有凸性。

于是,我们可以通过维护这个凸函数转折点来刻画这个函数,每次相当于将前一段斜率整体加 1,中间一段斜率不变,后一段斜率也整体加 1。我们可以用对顶堆来维护正负斜率,每次先向两个堆里扔进两个数(需要注意的是要加上整体偏移量),然后维护对顶堆的正确性,每次弹出来的两个元素累加答案即可,这相当于函数的平移。

Code

#include <bits/stdc++.h>
#define int long long
using namespace std;
priority_queue<int> q1;
priority_queue<int, vector<int>, greater<int>> q2;

signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);

    int n, h, ans = 0;
    cin >> n >> h;
    int lt = 0, rt = 0;
    for (int i = 1; i <= n; i ++ )
    {
        int x;
        cin >> x;
        lt += h, rt += h;
        q1.push(x + lt), q2.push(x - rt);

        int l = q1.top() - lt;
        int r = q2.top() + rt;

        while (l > r)
        {
            q1.pop();
            q2.pop();
            ans += l - r;
            q1.push(r + lt);
            q2.push(l - rt);
            l = q1.top() - lt, r = q2.top() + rt;
        }

    }

    cout << ans;

    return 0;
}