在一条数轴上有N家商店,它们的坐标分别为A1~AN。spa
如今须要在数轴上创建一家货仓,天天清晨,从货仓到每家商店都要运送一车商品。code
为了提升效率,求把货仓建在何处,可使得货仓到每家商店的距离之和最小。blog
第一行输入整数N。it
第二行N个整数A1~AN。io
输出一个整数,表示距离之和的最小值。class
1≤N≤100000效率
4 6 2 9 1
12
#include <cstdio> #include <algorithm> using namespace std; const int N = 100010; int x[N]; int n; int main() { scanf("%d", &n); for (int i = 0; i < n; i ++) scanf("%d", &x[i]); sort(x, x + n); int c = x[n / 2]; int ans = 0; for (int i = 0; i < n; i ++) ans += abs(x[i] - c); printf("%d", ans); return 0; }