在一條數軸上有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; }