跳到正文

题解

AT4166 题解

Yizhixiaoyun约 2 分钟
原文
文章信息与版本

文章信息

发布
2022年5月25日
收录
2026年10月14日
更新
2026年11月14日
篇幅
约 2 分钟
获赞
5

版本

  1. v1当前

题目传送门

题目分析

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

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

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

贴上代码

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

C++
#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();
}
原文