题目传送门

一、题意分析

AcWing 104. 货仓选址

二、算法思路

1、先想两个数\(a\)\(b\),在哪个位置建仓库最好?傻子都知道在中间最好!不信你放左边和右边试试!
背后的含义就是绝对值不等式: \(|x-a|+|x-b|>=|a-b|\),只有在中间时,\(|x-a|+|x-b|=|a-b|\),是最小值。

2、那如果不是两个数是多个数呢?
其实就是简单扩展一下,把所有的数排一下序,然后在中间找一下就行了。

举个例子

奇数个:$1\ 2\ 3\ 4\ 5\ $ ,\(n=5\), \(a[n/2]=a[2]=3\);

偶数个:\(1\ 2\ 3\ 4\) , \(n=4\), \(a[n/2]=a[2]=3\);其实我们在偶数时取\(2\)\(3\)都是可以的,所以统一写法:

获取中位数:
\(a[n/2]\)

三、实现代码

#include <bits/stdc++.h>

using namespace std;
const int N = 100010;
int n, res;
int a[N];

int main() {
    //优化输入
    ios::sync_with_stdio(false);
    cin >> n;
    for (int i = 0; i < n; i++)cin >> a[i];
    sort(a, a + n);

    for (int i = 0; i < n; i++) res += abs(a[i] - a[n / 2]);
    printf("%d", res);
    return 0;
}

相关文章:

  • 2022-12-23
  • 2021-06-13
  • 2021-05-23
  • 2021-07-25
  • 2022-02-24
  • 2022-12-23
猜你喜欢
  • 2021-09-18
  • 2022-12-23
  • 2021-04-02
  • 2021-11-08
  • 2021-06-24
  • 2021-06-27
  • 2021-11-18
相关资源
相似解决方案