Acwing104货仓选址

题目链接:https://www.acwing.com/problem/content/106/


题目:

在一条数轴上有 NN 家商店,它们的坐标分别为 A1~AN。

现在需要在数轴上建立一家货仓,每天清晨,从货仓到每家商店都要运送一车商品。

为了提高效率,求把货仓建在何处,可以使得货仓到每家商店的距离之和最小。

输入格式

第一行输入整数N。

第二行N个整数A1~AN。

输出格式

输出一个整数,表示距离之和的最小值。

数据范围

1N100000


输入样例:

4
6 2 9 1

输出样例:

12


 1 /*
 2  * @Descripttion: 
 3  * @version: https://www.acwing.com/problem/content/106/
 4  * @Author: ZKYAAA
 5  * @Date: 2020-04-07 20:18:56
 6  * @LastEditors: 请叫我ZK谕啊啊啊
 7  * @LastEditTime: 2020-04-07 21:04:18
 8  * ---------------------
 9  * 来源:《算法竞赛进阶指南》, 模板题
10  * 贪心思想:找到中位数得到的结果最优
11  * ---------------------
12  */
13 
14 #include <bits/stdc++.h>
15 using namespace std;
16 const int MAXN=100005;
17 int a[MAXN];
18 int n,sum=0,mid;
19 
20 int main(){
21     cin>>n;   
22     for(int i=0;i<n;i++)
23        cin>>a[i];
24     sort(a,a+n);
25     mid=a[n/2];
26     for(int i=0;i<n;i++){
27         sum+=abs(a[i]-mid);
28     }
29     cout<<sum<<endl;
30     return 0;
31 }
32 
33 
34  
原文地址:https://www.cnblogs.com/ZKYAAA/p/12656009.html