概述
问题 C: Linear Approximation
时间限制: 1 Sec 内存限制: 128 MB
[提交] [状态]
题目描述
Snuke has an integer sequence A of length N.
He will freely choose an integer b. Here, he will get sad if Ai and b+i are far from each other. More specifically, the sadness of Snuke is calculated as follows:
abs(A1−(b+1))+abs(A2−(b+2))+…+abs(AN−(b+N))
Here, abs(x) is a function that returns the absolute value of x.
Find the minimum possible sadness of Snuke.
Constraints
1≤N≤2×105
1≤Ai≤109
All values in input are integers.
输入
Input is given from Standard Input in the following format:
N
A1 A2 … AN
输出
Print the minimum possible sadness of Snuke.
样例输入 Copy
5
2 2 3 5 5
样例输出 Copy
2
提示
If we choose b=0, the sadness of Snuke would be abs(2−(0+1))+abs(2−(0+2))+abs(3−(0+3))+abs(5−(0+4))+abs(5−(0+5))=2. Any choice of b does not make the sadness of Snuke less than 2, so the answer is 2.
#include <iostream>
#include <cstdio>
#include <queue>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <map>
using namespace std;
#define INF 0x3f3f3f3f
int main()
{
int n,a[200010];
long long avg=0;
cin >> n;
for(int i=1; i<=n; i++){
cin >> a[i];
a[i] -= i;
}
sort(a+1,a+1+n);
avg = a[n/2+1];
long long ans = 0;
for(int i=1; i<=n; i++)
ans += abs(a[i]-avg);
cout << ans << endl;
return 0;
}
注意:avg = a[n/2+1];
不是n/2 因为下标从1开始
最后
以上就是微笑小鸽子为你收集整理的中位数——Linear Approximation的全部内容,希望文章能够帮你解决中位数——Linear Approximation所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复