#include namespace { #pragma GCC diagnostic ignored "-Wunused-function" #include #pragma GCC diagnostic warning "-Wunused-function" using namespace std; using namespace atcoder; #define rep(i,n) for(int i = 0; i < (int)(n); i++) #define rrep(i,n) for(int i = (int)(n) - 1; i >= 0; i--) #define all(x) begin(x), end(x) #define rall(x) rbegin(x), rend(x) template bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; } else return false; } template bool chmin(T& a, const T& b) { if (b < a) { a = b; return true; } else return false; } using ll = long long; using P = pair; using VI = vector; using VVI = vector; using VL = vector; using VVL = vector; template struct SlopeTrick { static constexpr T INF = std::numeric_limits::max() / 3; T min_f = 0; // acutual value of x in L is ADD_add_L(x) = x + add_L T add_L = 0, add_R = 0; std::priority_queue L; std::priority_queue, std::greater<>> R; T top_L() { return L.empty() ? -INF : L.top() + add_L; } T top_R() { return R.empty() ? +INF : R.top() + add_R; } void push_L(T x) { L.push(x - add_L); } void push_R(T x) { R.push(x - add_R); } T pushpop_L(T x) { T L_max = top_L(); if (x >= L_max) return x; L.pop(); push_L(x); return L_max; } T pushpop_R(T x) { T R_min = top_R(); if (x <= R_min) return x; R.pop(); push_R(x); return R_min; } // f(x) += c void add_constant(T c) { min_f += c; } // f(x) += max(x - a, 0) void add_right_slope(T a) { min_f += std::max(top_L() - a, 0); push_R(pushpop_L(a)); } // f(x) += max(a - x, 0) void add_left_slope(T a) { min_f += std::max(a - top_R(), 0); push_L(pushpop_R(a)); } // f(x) += abs(x - a) void add_v(T a) { add_right_slope(a); add_left_slope(a); } void shift(T a, T b) { assert(a <= b); add_L += a; add_R += b; } void shift(T a) { shift(a, a); } }; } int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; VI a(n); rep(i, n) cin >> a[i]; sort(all(a)); SlopeTrick st; for(int x: a) { st.shift(1); while(!st.R.empty()) st.R.pop(); st.add_v(x); } cout << st.min_f << '\n'; }