#include namespace DECLARATIONS { using namespace std; using ll = long long; using PI = pair; template using V = vector; using VI = V; #define _1 first #define _2 second #ifdef MY_DEBUG # define DEBUG(x) x #else # define DEBUG(x) #endif template inline void debug(T &A) { DEBUG( for (const auto &a : A) { cerr << a << " "; } cerr << '\n'; ) } template inline void debug_dim2(T &A) { DEBUG( for (const auto &as : A) { debug(as); } ) } template inline void debug(const char *format, Args const &... args) { DEBUG( fprintf(stderr, format, args ...); cerr << '\n'; ) } template string format(const std::string &fmt, Args ... args) { size_t len = std::snprintf(nullptr, 0, fmt.c_str(), args ...); std::vector buf(len + 1); std::snprintf(&buf[0], len + 1, fmt.c_str(), args ...); return std::string(&buf[0], &buf[0] + len); } } using namespace DECLARATIONS; const int MOD = 1000000007; int main() { std::ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; VI A(N); for (int i = 0; i < N; ++i) { cin >> A[i]; } sort(A.begin(), A.end()); ll INF = (ll)1e18; function dfs = [&](int l, int r, ll sum) { debug("dfs(%d, %d, %lld)", l, r, sum); // 分割するには4以上必要 if (r - l <= 3) return sum; ll sum1 = 0ll; ll sum2 = sum; int ix = -1; ll _sum1 = INF, _sum2 = INF; int n = r - l; for (int i = 0; i < n - 1; ++i) { int med1 = l + i/2; int med2 = l + (i + n) / 2; sum1 += A[l + i] - A[med1]; sum2 -= A[med2] - A[l + i]; debug("i:%d med1:%d med2:%d sum1:%lld sum2:%lld", i, med1, med2, sum1, sum2); if (min(i + 1, n - 1 - i) >= 2 && sum1 + sum2 < _sum1 + _sum2) { _sum1 = sum1; _sum2 = sum2; ix = i + 1; } } if (ix == -1) return sum; // 分割できなかった return dfs(l, l + ix, _sum1) + dfs(l + ix, r, _sum2); }; int m = N / 2; ll sum = accumulate(A.begin(), A.end(), 0ll, [&](ll acc, int a){ return acc + abs(a - A[m]); }); cout << dfs(0, N, sum); return 0; }