Contest Hunter 0501 货仓选址 - 中位数

传送门

题意:给定一个有n个数的序列,找一个数,使得这个数与其他数的差的绝对值之和最小。

思路:先对序列排序,假设该数为第p个数,则p左侧有p-1个数,右侧有n-p个数,若p向左移动1个单位,ans'=ans-(p-1)+(n-p);若p向右移动1个单位,ans''=ans-(n-p)+(p-1),因此要使影响最小,应使n-p=p-1,解得p=(n+1)/2。

所以该数为这个有序序列的中位数:当n为奇数时,p=(n+1)>>1;当n为偶数时,p在[n<<1,(n<<1)+1]之间都可以。

AC Code:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=100000+10;
typedef long long ll;
int a[N];
int main(){
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++) scanf("%d",&a[i]);
    sort(a+1,a+n+1);
    ll ans=0;
    int mid;
    if(n&1) mid=(n+1)>>1;
    else mid=n>>1;
    for(int i=1;i<=n;i++){
        ans+=abs(a[i]-a[mid]);
    }
    printf("%d",ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Loi-Brilliant/p/9425414.html