题目大意
给定 ,每次操作可以选择一个 增减一,求最小操作次数使得所有 。
数据范围:。
思路分析
朴素 dp 表示 的方案数,转移为 。
那么考虑凸优化,直接维护函数斜率的拐点,拓展操作相当于把斜率为 的区间左右分别平移 。
用两个堆维护斜率为正负两部分的拐点,需要支持全局加,打标记即可。
时间复杂度 。
代码呈现
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int MAXN=2e5+5;
int n,m,a[MAXN];
priority_queue <ll> L;
priority_queue <ll,vector<ll>,greater<ll>> R;
signed main() {
scanf("%d%d",&n,&m);
for(int i=1;i<=n;++i) scanf("%d",&a[i]);
ll tg=0,ht=0; L.push(a[1]),R.push(a[1]);
for(int i=2;i<=n;++i) {
tg+=m;
ll x=L.top()-tg,y=R.top()+tg;
if(a[i]<=x) {
ht+=abs(a[i]-x),L.pop(),L.push(a[i]+tg),L.push(a[i]+tg),R.push(x-tg);
} else if(y<=a[i]) {
ht+=abs(a[i]-y),R.pop(),R.push(a[i]-tg),R.push(a[i]-tg),L.push(y+tg);
} else L.push(a[i]+tg),R.push(a[i]-tg);
}
printf("%lld\n",ht);
return 0;
}