#include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; typedef unsigned long long ull; typedef vector vll; typedef vector> vvll; #define for1(i,n) for (ll i=0;i<(n);i++) #define for2(i,m,n) for (ll i=(m);i<(n);i++) #define for3(i,m,n,d) for (ll i=(m);i<(n);i+=(d)) #define DEBUG 0 template void dumplist(T list) { for (auto item : list) { cout << item << " "; } cout << endl; } ll Y[100010]; ll N; const ll inf = 1LL << 60; // [0,i) [i,N) ll calc(ll i) { if (i == 0) return inf; if (i == N) return inf; ll cost = 0; // 左側を合わせるコスト ll pivot = Y[i/2]; for2(j,0,i) { cost += abs(Y[j] - pivot); } // 右側を合わせるコスト pivot = Y[(N-i)/2+i]; for2(j,i,N) { cost += abs(Y[j] - pivot); } return cost; } void solve() { cin >> N; for1(i,N) cin >> Y[i]; sort(&Y[0],&Y[N]); if (Y[0] == Y[N-1]) { cout << 1 << endl; return; } ll l = 0; ll r = N; ll p1 = (r-l)*1/3+l; ll p2 = (r-l)*2/3+l; while (l < r - 10) { ll a1 = calc(p1); ll a2 = calc(p2); if (a1 > a2) { l = p1; } else { r = p2; } p1 = (r-l)*1/3+l; p2 = (r-l)*2/3+l; //cerr << l << " " << p1 << " " << p2 << " " << r << endl; } ll ans = inf; for2(i,l,r) { ans = min(ans, calc(i)); } cout << ans << endl; } int main() { do { solve(); } while (DEBUG); }