【解题报告】 CH0501 货仓选址

【解题报告】 CH0501 货仓选址

题目:货仓选址

解题思路:

中位数

中位数是一种美好的数,在数学中经常使用,这道题建立一个数组,读入数据,然后排序一下,假设货仓建在x处,x左边有p个商家,x右边有q个商家,如果p<q,那么把货仓向右移一个位置,距离之和就变小,类似地,p>q,就把货仓向左移一个位置,所以建在中间的时候距离之和最小

AC代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn=100005;
int a[maxn],n,ans,pos;
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    cin>>a[i];
    sort(a+1,a+1+n);
    int pos=a[n/2+1];
    for(int i=1;i<=n;i++)
    ans+=abs(a[i]-pos);
    cout<<ans<<endl;
    return 0;
}
本博文为wweiyi原创,若想转载请联系作者,qq:2844938982
原文地址:https://www.cnblogs.com/wweiyi2004/p/11312675.html