中位数:货仓选址

# 题意
一条数轴上有n家商店,用数组a来记录它们的坐标,现在需要再数轴上建一个坐标,求将货仓建在哪里式货仓到各个商店距离之和最小

# 题解

先将a[1]~a[n]排序设货仓在坐标x处,x左侧有P个,右侧有Q个,若P<Q,则当货仓右移一个单位,距离之和会变小,Q-P,同理P>Q,则左移会使变小P-Q,

故当P=Q时最优,奇数在n+1>>1处最优,偶数在n>>1 ~ n>>1 +1 都是最优的

 1 #include<bits/stdc++.h>
 2 #define pii pair<int,int>
 3 #define pb push_back
 4 #define fi first
 5 #define se second
 6 using namespace std;
 7 const int N=1e5+10;
 8 int n;
 9 int a[N];
10 int main(){
11     ios::sync_with_stdio(0);
12     cin.tie(0);
13     cout.tie(0);
14     cin>>n;
15     for(int i=1;i<=n;i++)
16         cin>>a[i];
17     sort(a,a+n);
18     int ans=0;
19     int f;
20     if(n&1)
21         f=a[(n+1)/2];
22     else
23         f=a[n/2];
24     for(int i=1;i<=n;i++)
25         ans+=abs(a[i]-f);
26     cout<<ans<<endl;
27 }

猜你喜欢

转载自www.cnblogs.com/hhyx/p/12405902.html