思路:易想到代价随公差的变化是一个凸函数,因此我们可以三分d,然后用玄学中位数法确定最终的数列。
加上nth_element跑的飞快,还有玄学剪枝法,连Int128都不用开了,跑了253ms
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <math.h>
#include <map>
#include <set>
#include <queue>
using namespace std;
#define endl '\n'
#define ll long long
#define int long long
const int maxn = 2e5 + 5;
int n,a[maxn];
ll b[maxn],c[maxn];
ll check(int x){
ll res = 0;
for (int i = 1; i < n; ++i) {
c[i] = c[i - 1] + x - b[i + 1];
}
nth_element(c,c + n / 2,c + n);
ll mid = c[n / 2];
for (int i = 0; i < n; ++i) {
ll y = mid - c[i];
res += abs(y);
}
return res;
}
signed main(){
std::ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
for (int i = 1; i <= n; ++i) {
b[i] = a[i] - a[i - 1];
}
int l = -1e13,r = 1e13;
if (n > 2e3) l /= n / 10 ,r /= n / 10;
while (l < r){
int midl = l + (r - l) / 3;
int midr = r - (r - l) / 3;
if (check(midl) <= check(midr)) r = midr - 1;
else l = midl + 1;
}
cout << check(l);
}