中位数——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 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开始

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值