#include #include #include #include #include #include #include #include #include #include #include #include #include #define debug_value(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << #x << "=" << x << endl; #define debug(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << x << endl; template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } using namespace std; typedef long long ll; template vector> vec2d(int n, int m, T v){ return vector>(n, vector(m, v)); } template vector>> vec3d(int n, int m, int k, T v){ return vector>>(n, vector>(m, vector(k, v))); } template void print_vector(vector v, char delimiter=' '){ if(v.empty()) { cout << endl; return; } for(int i = 0; i+1 < v.size(); i++) cout << v[i] << delimiter; cout << v.back() << endl; } using P = pair; int main(){ ios::sync_with_stdio(false); cin.tie(0); cout << setprecision(10) << fixed; int n; cin >> n; vector a(n); for(int i = 0; i < n; i++) cin >> a[i]; sort(a.begin(), a.end()); auto calc = [&](){ vector from_right(n); vector

buf = {P(a.back(), a.back())}; for(int i = n-2; i >= 0; i--){ auto [l, r] = buf.back(); ll ans = from_right[i+1]; if(l > a[i]){ from_right[i] = ans; buf.push_back({a[i], a[i]}); }else{ buf.pop_back(); ans += r-l+1; l = a[i]; r++; while(!buf.empty()){ auto [l0, r0] = buf.back(); if(l0 == r){ ans += r0-l0+1; r = r0+1; buf.pop_back(); }else{ assert(l0 > r); break; } } from_right[i] = ans; buf.push_back({l, r}); } // for(auto [l, r]: buf) cout << l << ',' << r << ' '; // cout << endl; } return from_right; }; auto r = calc(); // print_vector(r); for(int i = 0; i < n; i++) a[i] *= -1; reverse(a.begin(), a.end()); auto l = calc(); for(int i = 0; i < n; i++) a[i] *= -1; reverse(a.begin(), a.end()); reverse(l.begin(), l.end()); ll ans = 1e18; for(int i = 0; i < n; i++) chmin(ans, l[i]+r[i]); cout << ans << endl; }