题解:AT_agc040_e [AGC040E] Prefix Suffix Addition

· · 题解

好题。

Solution

首先如果只有第一种操作 / 第二种操作,那么答案就为 \sum\limits_{i=1}^{n+1} [a_i<a_{i-1}] / \sum\limits_{i=1}^{n+1} [a_i>a_{i-1}]。

然后可以发现本题就相当于将 a_i 拆分为 p_i+q_i,最小化 \sum\limits_{i=1}^{n+1} [p_i<p_{i-1}]+\sum\limits_{i=1}^{n+1} [q_i>q_{i-1}]。然后考虑这样一个暴力 DP,设 f_{x,y} 表示考虑前 x 个数,p_x=y 的答案最小是多少,状态转移方程就为 f_{x,y}=\min\limits_{i=0}^{a_{x-1}}\{f_{x-1,i}+[y<i]+[a_x-y>a_{x-1}-i]\}。

但是这样复杂度直接升天,继续挖掘性质。

为了方便观察,我们先移项得到 f_{x,y}=\min\limits_{i=0}^{a_{x-1}}\{f_{x-1,i}+[y<i]+[y<a_x-a_{x-1}+i]\}。然后不难发现对于同一个决策 i,y 越大答案越小,且极差不超过 2,将所有决策的答案取 min 后 f_{x,y} 显然仍然满足这两个性质,且对于 f_{x,y} 相同的一段,最优一定是取 y 最小的那个。

所以我们只需要记录一个 ans,p,q 分别表示 f_{x,y} 的最小值,以及 ans+1 和 ans 最小的位置,形式化来说就是:

f_{x,y}= \begin{cases} ans-2&y\in [0,p-1]\\ ans-1&y\in [p,q-1]\\ ans&y\in [q,a_x]\\ \end{cases}

现在的转移方程就为(为了方便,这里令 \Delta=a_x-a_{x-1}):

f_{x,y}=\min \begin{cases} ans+2+[y<\Delta]\\ ans+1+[y<p]+[y<\Delta+p]\\ ans+[y<q]+[y<\Delta+q] \end{cases}

然后考虑如何动态维护 ans,p,q,分类讨论:

时间复杂度 O(n)。

Code

//when you use vector or deque,pay attention to the size of it.
//by OldDirverTree
#include<bits/stdc++.h>
//#include<atcoder/all>
#define P pair<int,int>
#define int long long
#define mid (l+r>>1)
using namespace std;
//using namespace atcoder;
//using mint=modint998244353;
int n,ans,p,q;

struct custom_hash
{
    static uint64_t splitmix64(uint64_t x) {
        x+=0x9e3779b97f4a7c15;
        x=(x^(x>>30) )*0xbf58476d1ce4e5b9;
        x=(x^(x>>27) )*0x94d049bb133111eb;
        return x^(x>>31);
    }
    size_t operator() (uint64_t x) const {
        static const uint64_t FIXED_RANDOM=chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x+FIXED_RANDOM);
    }
};
int read() {
    int x=0; bool _=true; char c=0;
    while (!isdigit(c) ) _&=(c!='-'),c=getchar();
    while (isdigit(c) ) x=x*10+(c&15),c=getchar();
    return _?x:-x;
}
main()
{
    n=read();
    for (int i=1,lst=0;i<=n+1;i++) {
        int val=i<=n?read():0;
        if (val<q) ans++,q=max(min(p,val-lst+q),0ll),p=0;
        else if (val<lst) p=max(min(p,val-lst+q),0ll);
        else p=min(p+val-lst,q),q+=val-lst; lst=val;
    }
    printf("%lld",ans);
    return 0;
}