C++
$\color{#cc33ff}{— > 算法基础课题解}$
$\color{gold}{— > 蓝桥杯辅导课题解}$
思路:
贪心
$图解:$
$时间复杂度:O(n)$
$code1:$
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1e5 + 10;
int n;
int a[N];
int main() {
cin >> n;
for (int i = 0; i < n; i ++) cin >> a[i];
sort (a, a + n);
int res = 0;
for (int i = 0; i < n; i ++) res += abs(a[i] - a[n / 2]);
cout << res;
return 0;
}
$code2:$
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
typedef long long ll;
int n;
int x[N];
int main() {
cin >> n;
for (int i = 0; i < n; i ++) cin >> x[i];
sort(x, x + n);
int c = x[n / 2];
ll res = 0;
for (int i = 0; i < n; i ++) res += abs(x[i] - c);
cout << res;
return 0;
}