中位数——Linear Approximation

阅读: 评论:0

中位数——Linear Approximation

中位数——Linear Approximation

问题 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 0x3f3f3f3fint 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开始

本文发布于:2024-02-05 04:52:06,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170724557863199.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23