题解:P8175 [CEOI 2021] Tortoise
有意思的题。
设每个位置与最近的空地距离为
很容易发现,最优的策略一定是从左到右的访问商店。
一个比较 trivial 的想法是,每选择一个数,就要多浪费
还有一种情况,称为决策 2:存在一个
发现这个就不是很好做,因为在一个商店购买若干物品的代价甚至还可能和下一个你要去商店的位置有关。我们再考虑决策 2,如果我们在
所以如果做了决策 2 则
也就是说我们可以在
#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;
}