每日一题——货仓选址

题目

货仓选址

题解

这是一道典型的思维题,我们不难看出在中间可以做到和为最小,所以我们只需要找出中间那个数即可。如果个数为奇数,那么就是中间那个值;如果为偶数,中间左右都是一样的,我们可以由数学知识证得。那么只需要给这个数组排个序找出中间那个值,然后再枚举加一遍就完成了。

参考代码

#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1e5 + 10;
int n;
int a[N];
int main(){
    cin >> n;
    for(int i = 1; i <= n; i ++) cin >> a[i];
    sort(a + 1, a + n + 1);
    int t = a[(1 + n) / 2];
    long long res = 0;
    for(int i = 1; i <= n; i ++) res += abs(t - a[i]);
    cout << res << endl;
    return 0;
}
posted @ 2025-03-13 18:45  PZnwbh  阅读(14)  评论(0)    收藏  举报