AT4166 题解

· · 题解

题目传送门

题目分析

通项公式:|(a_i - i) - b)|

那么我们就可以发现,如果希望式子最小,那么 (a_i - i) 与 b 之间的差就要尽量小。

我们可以使用另外一个数组 q ,使 q_i = a_i - i ,然后对其排序,排序后将 b 取 q_{(n+1)/2} ,即可与 (a_i - i) 差值最小。

贴上代码

十年 \text{oi} 一场空,没开 \text{long long} 见祖宗!

#include<bits/stdc++.h>
#define pb push_back
#define pf push_front
#define ass assign
#define fst first
#define sec second
#define lb lower_bound
#define ub upper_bound
#define zltAKIOI 1
using namespace std;
const int maxn=200005;
long long n,a[maxn];
long long x,ans;
void init(){
    cin>>n;
    for(register long long i=1;i<=n;++i){
        cin>>x;a[i]=x-i;
    }
}
void duel(){
    sort(a+1,a+n+1);
    for(register long long i=1;i<=n;++i) ans+=abs(a[i]-a[(i+1)>>1]);
}
void print(){
    cout<<ans<<endl;
}
int main(){
    init();
    duel();
    print();
}