题解:P8175 [CEOI 2021] Tortoise

· · 题解

有意思的题。

设每个位置与最近的空地距离为 d_i,设被选了至少一次的位置为 S,考虑如果钦定一个 S,最优的策略。

很容易发现,最优的策略一定是从左到右的访问商店。

一个比较 trivial 的想法是,每选择一个数,就要多浪费 2d_i 的时间(从商店跑到最近的空地再跑回来),显然是不对的。考虑最后一次买商品的时候,实际上没有必要回到原点,如果当前在商店 a,下一步要去商店 b,[a,b] 间存在一个空地,那我们带着最后一个商品直接往前走就可以,这就不需要花费额外的时间。

还有一种情况,称为决策 2:存在一个 c>b 使得 c 是空地,这时会花费额外的 2c-a-b 的时间。

发现这个就不是很好做,因为在一个商店购买若干物品的代价甚至还可能和下一个你要去商店的位置有关。我们再考虑决策 2,如果我们在 b 点购买了一件商品,运到 c,代价只需要 2c-2b,这个数比 2c-a-b 小。更进一步的,设 a 右边第一个商店是 p_a,则如果我们做了决策 2,p_a 应该被选满,否则可以进行调整。

所以如果做了决策 2 则 a 在 S 中的后继一定是 p_a,否则做决策 2 不优,再设 a 后面第一个空地位置是 q_a,我们可以等价的认为在 a 位置上购买的最后一个商品需要额外花费的时间是 c_a = \min(2d_a,\max (0,2q_a-2p_a))。

也就是说我们可以在 a 位置买一个代价为 c_a 的商品,也可以在 a 位置买不超过上限个代价为 2d_a 的商品,要求如果当前在位置 i 则花费的总代价不能超过 i-1。这个问题可以简单的用反悔贪心解决。

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int inf = 10000000000;
int n;
int a[500005],pre[500005],nxt[500005],pos[500005];
priority_queue<int>q;
signed main(){
    cin >> n;
    for(int i =1;i<=n;i++)cin >> a[i];
    pre[0] = -inf;for(int i = 1;i<=n;i++){if(a[i]==-1)pre[i]=i;else pre[i] = pre[i-1];}
    nxt[n+1] =inf;for(int i = n;i>=1;i--){if(a[i]==-1)nxt[i]=i;else nxt[i] = nxt[i+1];}
    int p = 0;
    for(int i = n;i>=1;i--){
        if(a[i]==0)continue;
        if(a[i]==-1)p = 0;
        else pos[i] = p,p = i;
    }
    int ans = 0,tot = 0;
    for(int i = 1;i<=n;i++){
        if(a[i] == 0 or a[i] == -1)continue;
        int d = min(i-pre[i],nxt[i]-i)*2;
        for(int j = 1;j<a[i];j++){
            if(tot<=i-1){
                q.push(d);
                tot += d;
                ++ans;
            }else if(q.size() and d<q.top()){
                tot -= q.top();
                q.pop();
                tot += d;
                q.push(d);
            }else break;
        }
        if(!pos[i])d = 0;
        else d = min(i-pre[i],nxt[i]-pos[i])*2;
        if(tot<=i-1){
            q.push(d);
            tot += d;
            ++ans;
        }else if(q.size() and d<q.top()){
            tot -= q.top();
            q.pop();
            tot += d;
            q.push(d);
        }
    }
    replace(a+1,a+1+n,-1,0);
    int res = accumulate(a+1,a+1+n,0)-ans;
    cout << res << endl;
    return 0;
}