Problem:
B: Warp Points
You are constructing an interstellar transportation network. There are $N$ stars in your area, and your task is to make it possible to go to any star from any star. Currently, all of these stars are isolated, and we cannot go anywhere from each star.
As an interstellar transportation network designer, you can set warp points. Stars are numbered from $1$ to $N$, and a warp point enables coming and going between consecutively numbered stars. The construction cost for a warp point depends on the "potentials" for stars and the warp point. The potential for $i$-th star is given as an integer, and you can set the potential for the warp point to any integer. The cost is calculated as the summation of the absolute difference between the warp point's potential and each contained star's potential.
You can construct any number of warp points. Your task is to calculate the minimum total cost to enable coming and going between any
pair of stars using some warp points.
For the sample input 1, you should plan to construct one warp point with potential 2.
For the sample input 2, three warp points are needed to minimize the total cost. The first warp point connects from the first to the fourth star. The second warp point connects from the fourth to the sixth stars. The third warp point connects from the sixth to tenth stars.
Input
The input consists of a single test case of the following format.
$N$
$a_1$ ... $a_N$
$N$ represents the number of stars ($1 \leq N \leq 3,000$). Numbers $a_1$ through $a_N$ are the potentials of the stars. It is guaranteed that these
potentials are integers in the range between $-1,000,000,000$ and $1,000,000,000$.
Output
Output the minimum total cost to connect all stars.
Examples
Input 1
3
2 5 2
Output 1
3
Input 2
10
1 2 3 2 1 10 9 8 9 10
Output 2
14

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using PLL = pair<ll, ll>;
#define rep(i, n) for (ll i = 0; i < n; ++i)
#define loop(i, a, b) for (ll i = a; i <= b; ++i)
#define vll vector<ll>
#define vvll vector<vll>
constexpr ll INF = 9009009009009009009LL;

int main() {
    ll n; cin >> n;
    vll a(n); rep(i, n) cin >> a[i];

    vector<vector<PLL>> g(n);
    rep(s, n) {
        priority_queue<ll> small;
        priority_queue<ll, vector<ll>, greater<ll>> big;
        ll smallSum = 0, bigSum = 0, center = a[s];

        loop(i, s + 1, n - 1) {
            if (center != INF) {
                ll x = a[i], y = center;
                if (y < x) swap(x, y);
                small.push(x);
                smallSum += x;
                big.push(y);
                bigSum += y;
                center = INF;
            }
            else {
                if (a[i] < small.top()) {
                    small.push(a[i]);
                    smallSum += a[i];
                    center = small.top();
                    smallSum -= small.top();
                    small.pop();
                }
                else if (big.top() < a[i]) {
                    big.push(a[i]);
                    bigSum += a[i];
                    center = big.top();
                    bigSum -= big.top();
                    big.pop();
                }
                else {
                    center = a[i];
                }
            }
            g[s].push_back({i, bigSum - smallSum});
        }
    }

    vector<ll> dp(n, INF);
    dp[0] = 0;
    rep(i, n) {
        for (auto [to, cost] : g[i]) {
            dp[to] = min(dp[to], dp[i] + cost);
        }
    }

    cout << dp[n - 1] << endl;
    return 0;
}
accuracy: 1
time_ms: 150
memory_kb: 86272
final_rank: 11

code_snippet: #include<bits/extc++.h>
#define rep(i,n) for(int i = 0; i<(n); i++)
#define all(a) begin(a),end(a)
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int mod = 998244353;
const int inf = (1<<30);
const ll INF = (1ull<<62);
const int dx[8] = {1,0,-1,0,1,1,-1,-1};
const int dy[8] = {0,1,0,-1,1,-1,1,-1};
template<typename T1, typename T2>
inline bool chmax(T1 &a, T2 b){ return a < b && (a = b, true);}
template<typename T1, typename T2>
inline bool chmin(T1 &a, T2 b){ return a > b && (a = b, true);}

int main(){
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    cout.setf(ios_base::fixed);
    cout.precision(12);

    int n; cin>>n;
    vector<int> a(n+1); rep(i,n) cin>>a[i];

    vector<ll> dp(n,INF);
    dp[0] = 0;

    for(int i = 0; i<n; i++){

        priority_queue<ll,vector<ll>,greater<ll>> r;
        priority_queue<ll> l;
        l.push(a[i]);
        ll rsum = 0, lsum = a[i];
        for(int j = i+1; j<n; j++){
            
            if(r.size()+1 == l.size()){
                r.push(a[j]);
                rsum += a[j];
            }else{
                l.push(a[j]);
                lsum += a[j];
            }
            if(r.top() < l.top()){
                int x = r.top(); r.pop(); rsum -= x;
                int y = l.top(); l.pop(); lsum -= y;
                r.push(y);
                l.push(x);
                rsum += y;
                lsum += x;
            }
            int y = l.top();
            ll cost = (ll(l.size()) * y - lsum) + (rsum - ll(r.size())*y);
            //cout<<cost<<" "<<i<<" "<<j<<" "<<y<<endl;
            dp[j] = min(dp[j], dp[i] + cost);
        }
    }
    cout<<dp[n-1]<<endl;

}
accuracy: 1
time_ms: 220
memory_kb: 3524
final_rank: 6

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f3f3f3f3f
#define endl '\n'
#define int long long
//#define double long double
#define pb push_back
#define pii pair<int, int>
#define all(x) x.begin(), x.end()
#define odebug freopen("out.txt", "w", stdout)
#define sz size

#define N 3005

int dp[N][N];
int ans[N];
int a[N];

struct ll
{
	int val;
	friend bool operator<(ll x,ll b)
	{
		return x.val<b.val;
	}
};

struct rr
{
	int val;
	friend bool operator<(rr x,rr b)
	{
		return x.val>b.val;
	}
};

signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
		dp[i][i]=a[i];
	}
	for(int i=1;i<=n;i++)
	{
		priority_queue<ll> l;
		priority_queue<rr> r;
		int sl=0,sr=0;
		l.push((ll){a[i]});
		sl+=a[i];
		for(int j=i+1;j<=n;j++)
		{
			if((int)l.size()>(int)r.size())
			{
				int pre=l.top().val;
				int now=a[j];
				if(now>=pre)
				{
					r.push((rr){now});
					sr+=now;
				}
				else
				{
					l.pop();
					l.push((ll){now});
					sl=sl-pre+now;
					r.push((rr){pre});
					sr+=pre;
				}
			}
			else
			{
				int pre=r.top().val;
				int now=a[j];
				if(now<=pre)
				{	
					l.push((ll){now});
					sl+=now;
				}
				else
				{
					r.pop();
					r.push((rr){now});
					sr=sr-pre+now;
					l.push((ll){pre});
					sl+=pre;
				}
			}
			int mid=l.top().val;
			dp[i][j]=mid*(int)l.size()-sl+sr-mid*(int)r.size();
		}
	}
	fill(ans,ans+n+1,inf);
	ans[1]=0;
	for(int i=2;i<=n;i++)
	{
		for(int j=1;j<i;j++)
		{
			ans[i]=min(ans[i],ans[j]+dp[j][i]);
		}
	}
	cout<<ans[n]<<endl;
}
accuracy: 1
time_ms: 160
memory_kb: 73200
final_rank: 10

code_snippet: #include<bits/stdc++.h>
// #include<atcoder/all>
// #include<boost/multiprecision/cpp_int.hpp>

using namespace std;
// using namespace atcoder;
// using bint = boost::multiprecision::cpp_int;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
using vi = vector<ll>;
using vvi = vector<vi>;
using vvvi = vector<vvi>;
using ve = vector<vector<int>>;
using vb = vector<bool>;
using vvb = vector<vb>;
#define rep(i,s,n) for(ll i = (ll)s;i < (ll)n;i++)
#define rrep(i,l,r) for(ll i = r-1;i >= l;i--)
#define ALL(x) (x).begin(),(x).end()
#define sz(c) ((ll)(c).size())
#define LB(A,x) (int)(lower_bound(A.begin(),A.end(),x)-A.begin())
#define UB(A,x) (int)(upper_bound(A.begin(),A.end(),x)-A.begin())
// #define MOD 1000000007
#define MOD 998244353
template<typename T>using min_priority_queue=priority_queue<T,vector<T>,greater<T>>;
template<typename T>ostream&operator<<(ostream&os,vector<T>&v){for(int i = 0;i < v.size();i++)os<<v[i]<<(i+1!=v.size()?" ":"");return os;}
template<typename T>istream&operator>>(istream&is,vector<T>&v){for(T&in:v)is>>in;return is;}
template<typename T1,typename T2>ostream&operator<<(ostream&os,pair<T1,T2>&p){os<<p.first<<" "<<p.second;return os;}
template<typename T1,typename T2>istream&operator>>(istream&is,pair<T1,T2>&p){is>>p.first>>p.second;return is;}
template<typename T> inline bool chmax(T &a,T b){if(a < b){a = b;return true;}return false;}
template<typename T> inline bool chmin(T &a,T b){if(a > b){a = b;return true;}return false;}
ld dist(ld x1,ld y1,ld x2, ld y2){return sqrtl((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));}


int main(){
  
  ios_base::sync_with_stdio(0), cin.tie(0);
  int n;cin >> n;
  vi a(n);cin >> a;
  const ll inf = 1ll << 60;
  vi dp(n,inf);
  dp[0] = 0;
  rep(i,1,n){
    ll S1 = 0,S2 = 0;
    priority_queue<int> que1;
    min_priority_queue<int> que2;
    auto balance = [&](ll k){
      ll m = -1;
      if(sz(que1))m = que1.top();
      if(k <= m){
        que1.push(k);S1 += k;
        while(sz(que2)+1 < sz(que1)){
          ll x = que1.top();
          que1.pop();S1 -= x;
          que2.push(x);S2 += x;
        }
      }else{
        que2.push(k);S2 += k;
        while(sz(que1) < sz(que2)){
          ll x = que2.top();
          que2.pop();S2 -= x;
          que1.push(x);S1 += x;
        }
      }
    };
    balance(a[i]);
    rrep(j,0,i){
      balance(a[j]);
      ll m = que1.top();
      chmin(dp[i],dp[j] + S2-sz(que2)*m + sz(que1)*m-S1);
    }
  }
  cout << dp[n-1] << endl;
  

  return 0;
}
accuracy: 1
time_ms: 160
memory_kb: 3584
final_rank: 5

code_snippet: #include <iostream>
#include <iomanip>
#include <cassert>
#include <vector>
#include <algorithm>
#include <utility>
#include <numeric>
#include <tuple>
#include <ranges>
#include <queue>
namespace ranges = std::ranges;
namespace views = std::views;
// #include "Src/Number/IntegerDivision.hpp"
// #include "Src/Utility/BinarySearch.hpp"
// #include "Src/Sequence/CompressedSequence.hpp"
// #include "Src/Sequence/RunLengthEncoding.hpp"
// #include "Src/Algebra/Group/AdditiveGroup.hpp"
// #include "Src/DataStructure/FenwickTree/FenwickTree.hpp"
// #include "Src/DataStructure/SegmentTree/SegmentTree.hpp"
// using namespace zawa;
// #include "atcoder/modint"
// using mint = atcoder::modint998244353;
struct Median {
    std::priority_queue<int> sm;
    std::priority_queue<int, std::vector<int>, std::greater<int>> bg;
    long long sms = 0, bgs = 0;
    Median() = default;
    void push(int v) {
        if (sm.empty() and bg.empty()) {
            sms += v;
            sm.push(v);
        }
        else if (sm.top() <= v) {
            bgs += v;
            bg.push(v);
        }
        else {
            sms += v;
            sm.push(v);
        }
        while (sm.size() > bg.size()) {
            sms -= sm.top();
            bgs += sm.top();
            bg.push(sm.top());
            sm.pop();
        }
        while (sm.size() + 1 < bg.size()) {
            bgs -= bg.top();
            sms += bg.top();
            sm.push(bg.top());
            bg.pop();
        }
    }
    long long eval() const {
        if (sm.empty() and bg.empty()) return 0LL;
        assert(bg.size());
        const long long m = bg.top();
        return bgs - m * bg.size() + m * sm.size() - sms;
    }
};
int N, A[3000];
int main() {
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);
    std::ios::sync_with_stdio(false);
    std::cin >> N;
    for (int i = 0 ; i < N ; i++) std::cin >> A[i];
    std::vector<long long> dp(N);
    {
        Median med;
        for (int i = 0 ; i < N ; i++) {
            med.push(A[i]);
            dp[i] = med.eval();
        }
    }
    for (int i = 0 ; i < N ; i++) {
        Median med;
        med.push(A[i]);
        for (int j = i + 1 ; j < N ; j++) {
            med.push(A[j]);
            dp[j] = std::min(dp[j], dp[i] + med.eval());
        }
    }
    std::cout << dp[N - 1] << '\n';
}
accuracy: 1
time_ms: 150
memory_kb: 3712
final_rank: 3

code_snippet: // AOJ #3219 Warp Points
// 2025.2.24

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = 1LL << 60;

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);

    int N;
    cin >> N;
    vector<ll> a(N);
    for (int i = 0; i < N; i++) cin >> a[i];

    vector<ll> dp(N, INF);
    dp[0] = 0;

    for (int j = 0; j < N; j++){
        priority_queue<ll> left;
        priority_queue<ll, vector<ll>, greater<ll>> right;
        ll sumL = 0, sumR = 0;
        for (int i = j; i < N; i++){
            if(left.empty() || a[i] <= left.top()){
                left.push(a[i]);
                sumL += a[i];
            } else {
                right.push(a[i]);
                sumR += a[i];
            }
            if(left.size() < right.size()){
                ll val = right.top();
                right.pop();
                sumR -= val;
                left.push(val);
                sumL += val;
            } else if(left.size() > right.size() + 1){
                ll val = left.top();
                left.pop();
                sumL -= val;
                right.push(val);
                sumR += val;
            }

            if(i - j >= 1){
                ll median = left.top();
                int cntL = left.size();
                int cntR = right.size();
                ll cost = median * cntL - sumL + sumR - median * cntR;
                dp[i] = min(dp[i], dp[j] + cost);
            }
        }
    }
    cout << dp[N-1] << endl;
    return 0;
}
accuracy: 1
time_ms: 160
memory_kb: 3576
final_rank: 4

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(ll i=0; i < (ll)(n); i++)
#define rrep(i, s, e) for(ll i=s; i>= (ll)(e); i--)
#define repn(i, e) for (ll i=0; i <= (ll)(e); i++)
#define reps(i, s,e) for(ll i=s; i < (ll)(e); i++ )
#define repsn(i,s,e) for(ll i=s; i<=(ll)(e); i++)
#define each(p,a) for(auto &p: a)
typedef vector<ll> vll;
typedef vector<vector<ll>> vvll;
typedef pair<ll, ll> pll;
typedef vector<pair<ll,ll>> vpll;
typedef pair<ll,ll> pll;
typedef vector<pair<ll, ll>> vpll;
typedef tuple<ll, ll, ll> tpl3;
#define all(a) (a).begin(), (a).end()
#define sz(x) (ll)x.size()
template<class T> bool chmin(T& a, T b) { if (a > b) {a = b; return true;} return false;}
template<class T> bool chmax(T& a, T b) { if (a < b) {a =b; return true;} return false;}
vector<ll> _ta = {0,0,1,-1,1,1,-1,1};
vector<ll> _yo = {1,-1,0,0,1,-1,1,-1};
bool isin(ll i, ll j, ll h, ll w) {return (0 <= i && i < h && 0 <= j && j < w);}
ll INF = 1LL << 60;

int main() {
  ll n;cin >> n;
  vll a(n);
  rep(i,n) {
    cin >> a[i];
  }

  vvll cost(n,vll(n));
  rep(i,n) {
    ll maesum = 0;
    ll ushsum = 0;
    multiset<ll> mae,ush;

    reps(j,i,n) {
      mae.insert(a[j]);
      maesum += a[j];
      while (!mae.empty() && !ush.empty() && *mae.rbegin() > *ush.begin()) {
        ll mb = *mae.rbegin();
        ll uf = *ush.begin();
        mae.erase(mae.find(mb));
        ush.erase(ush.find(uf));
        mae.insert(uf);
        ush.insert(mb);
        maesum += -mb + uf;
        ushsum += mb - uf;
      }
      while (sz(mae) > sz(ush) + 1) {
        ll mb = *mae.rbegin();
        ush.insert(mb);
        mae.erase(mae.find(mb));
        maesum -= mb;
        ushsum += mb;
      }
      while (sz(ush) > sz(mae) + 1) {
        ll uf = *ush.begin();
        mae.insert(uf);
        ush.erase(ush.find(uf));
        maesum += uf;
        ushsum -= uf;
      }
      auto clccost =[&](ll mid) {
        return mid * sz(mae) - maesum + ushsum - mid * sz(ush);
      };
      if (sz(mae) == sz(ush)) {
        ll mb = *mae.rbegin();
        ll uf = *ush.begin();
        ll m1 = (mb+uf)/2;
        ll m2 = m1+1;
        cost[i][j] = min(clccost(m1),clccost(m2));
      }else if (sz(mae) > sz(ush)) {
        cost[i][j] = clccost(*mae.rbegin());
      }else {
        cost[i][j] = clccost(*ush.rbegin());
      }
    }

  }

  // //dbg
  // rep(i,n) {
  //   rep(j,n) {
  //     cout << cost[i][j] << " ";
  //   }
  //   cout << endl;
  // }

 //greedy
  vll dp(n,INF);//saigoni oitanoga i
  dp[0] = 0;
  reps(i,1,n) {
    rrep(j,i-1,0) {
      chmin(dp[i],dp[j] + cost[j][i]);
    }
  }
  cout << dp[n-1] << endl;
  return 0;
}
accuracy: 1
time_ms: 800
memory_kb: 73812
final_rank: 16

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

/**
 * @brief template
 */

int main() {
    int N;
    cin >> N;
    vector<ll> A(N);
    rep(i,0,N) cin >> A[i];
    vector<ll> DP(N,INF);
    DP[0] = 0;
    rep(i,1,N) {
        priority_queue<ll> L;
        priority_queue<ll,vector<ll>,greater<ll>> R;
        L.push(A[i]);
        ll LSUM = A[i], RSUM = 0;
        rrep(j,0,i) {
            ll MID = L.top();
            if (A[j] < MID) {
                LSUM += A[j];
                L.push(A[j]);
                while (L.size() > R.size() + 1) {
                    LSUM -= L.top();
                    RSUM += L.top();
                    R.push(L.top());
                    L.pop();
                }
            }
            else {
                RSUM += A[j];
                R.push(A[j]);
                while (L.size() < R.size()) {
                    RSUM -= R.top();
                    LSUM += R.top();
                    L.push(R.top());
                    R.pop();
                }
            }
            MID = L.top();
            ll X = MID * L.size() - LSUM + RSUM - MID * R.size();
            chmin(DP[i], DP[j]+X);
        }
    }
    cout << DP[N-1] << endl;
}
accuracy: 1
time_ms: 150
memory_kb: 3572
final_rank: 1

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

/**
 * @brief template
 */

int main() {
    int N;
    cin >> N;
    vector<ll> A(N);
    rep(i,0,N) cin >> A[i];
    vector<ll> DP(N,INF);
    DP[0] = 0;
    rep(i,1,N) {
        priority_queue<ll> L;
        priority_queue<ll,vector<ll>,greater<ll>> R;
        L.push(A[i]);
        ll LSUM = A[i], RSUM = 0;
        rrep(j,0,i) {
            ll MID = L.top();
            if (A[j] < MID) {
                LSUM += A[j];
                L.push(A[j]);
                LSUM -= MID;
                RSUM += MID;
                L.pop();
                R.push(MID);
            }
            else {
                RSUM += A[j];
                R.push(A[j]);
                while (L.size() < R.size()) {
                    RSUM -= R.top();
                    LSUM += R.top();
                    L.push(R.top());
                    R.pop();
                }
            }
            MID = L.top();
            ll X = MID * L.size() - LSUM + RSUM - MID * R.size();
            chmin(DP[i], DP[j]+X);
        }
    }
    cout << DP[N-1] << endl;
}
accuracy: 0.5238095238095238
time_ms: 220
memory_kb: 3544
final_rank: 17

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vll>;
#define rep(i,n) for(ll i=0;i<ll(n);i++)

const ll mod = 1e9 + 7;

struct Halfset{
    multiset<ll> Upperset,Lowerset;
    ll Uppersum=0,Lowersum=0;

    void narasu(){
        while(int(Lowerset.size())>int(Upperset.size())){
            int p=*(prev(Lowerset.end()));
            Lowerset.erase(Lowerset.find(p));
            Lowersum-=p;
            Uppersum+=p;
            Upperset.insert(p);
        }
        while(int(Lowerset.size())+1<int(Upperset.size())){
            int p=*(Upperset.begin());
            Upperset.erase(Upperset.find(p));
            Lowersum+=p;
            Uppersum-=p;
            Lowerset.insert(p);
        }
    }

    void insert(ll x){
        if(*(Upperset.begin())<x){
            Upperset.insert(x);
            Uppersum+=x;
        }
        else{
            Lowerset.insert(x);
            Lowersum+=x;
        }
        narasu();
    }
};

int main() {
    
    ll N;
    cin>>N;
    vll X(N);
    rep(i,N)cin>>X[i];
    vll DP(N,1e18);
    DP[0]=0;
    for(ll i=0;i<N;i++){
        Halfset S;
        S.insert(X[i]);
        for(ll j=i+1;j<N;j++){
            S.insert(X[j]);
            ll up=S.Uppersum;
            ll down=S.Lowersum;
            ll p=*(S.Upperset.begin());
            ll cost=up-p*ll(S.Upperset.size())+p*ll(S.Lowerset.size())-down;
            DP[j]=min(DP[j],DP[i]+cost);
        }
    }
    cout<<DP[N-1]<<endl;

}
accuracy: 1
time_ms: 480
memory_kb: 3632
final_rank: 8

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vll>;
#define rep(i,n) for(ll i=0;i<ll(n);i++)

const ll mod = 1e9 + 7;

struct Halfset{
    multiset<ll> Upperset,Lowerset;
    ll Uppersum=0,Lowersum=0;

    void narasu(){
        while(int(Lowerset.size())>int(Upperset.size())){
            int p=*(prev(Lowerset.end()));
            Lowerset.erase(Lowerset.find(p));
            Lowersum-=p;
            Uppersum+=p;
            Upperset.insert(p);
        }
        while(int(Lowerset.size())+1<int(Upperset.size())){
            int p=*(Upperset.begin());
            Upperset.erase(Upperset.find(p));
            Lowersum+=p;
            Uppersum-=p;
            Lowerset.insert(p);
        }
    }

    void insert(ll x){
        if(*(Upperset.begin())<x){
            Upperset.insert(x);
            Uppersum+=x;
        }
        else{
            Lowerset.insert(x);
            Lowersum+=x;
        }
    }
};

int main() {
    
    ll N;
    cin>>N;
    vll X(N);
    rep(i,N)cin>>X[i];
    vll DP(N,1e18);
    DP[0]=0;
    for(ll i=0;i<N;i++){
        Halfset S;
        S.insert(X[i]);
        for(ll j=i+1;j<N;j++){
            S.insert(X[j]);
            ll up=S.Uppersum;
            ll down=S.Lowersum;
            ll p=*(S.Upperset.begin());
            ll cost=up-p*ll(S.Upperset.size())+p*ll(S.Lowerset.size())-down;
            DP[j]=min(DP[j],DP[i]+cost);
        }
    }
    cout<<DP[N-1]<<endl;

}
accuracy: 0.047619047619047616
time_ms: 160
memory_kb: 3540
final_rank: 18

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 2 "cp-library/src/data_structure/fenwick_tree.hpp"

template < class comm_monoid > class fenwick_tree {
  public:
    using T = typename comm_monoid::set;

  private:
    int n, n2;
    vector< T > data;

    int ceil_pow2(int n) {
        int x = 1;
        while(x < n) x <<= 1;
        return x;
    }

  public:
    fenwick_tree() : fenwick_tree(0) {}
    fenwick_tree(int n) : n(n), n2(ceil_pow2(n)), data(n + 1, comm_monoid::id()) { assert(comm_monoid::comm); }
    fenwick_tree(const vector< T > &a) : n(a.size()), n2(ceil_pow2(n)), data(a) {
        assert(comm_monoid::comm);
        data.insert(data.begin(), {comm_monoid::id()});
        for(int i = 1; i <= n; i++) {
            int p = i + (i & -i);
            if(p <= n) data[p] = comm_monoid::op(data[i], data[p]);
        }
    }

    void add(int i, T x) {
        for(int p = i + 1; p <= n; p += p & -p) data[p] = comm_monoid::op(data[p], x);
    }
    // [0, r)
    T fold(int r) {
        T s = comm_monoid::id();
        for(int p = r; p > 0; p -= p & -p) s = comm_monoid::op(data[p], s);
        return s;
    }
    // [l, r)
    T fold(int l, int r) {
        return comm_monoid::op(comm_monoid::inv(fold(l)), fold(r));
    }
    T get(int i) {
        return fold(i, i + 1);
    }
    void set(int i, T x) {
        add(i, comm_monoid::op(comm_monoid::inv(get(i)), x));
    }
    template< class func > int search(const func &f) {
        T s = comm_monoid::id();
        if(f(s)) return 0;
        int i = 0, k = n2;
        while(k >>= 1) {
            int p = i | k;
            if(p <= n && !f(comm_monoid::op(s, data[p]))) s = comm_monoid::op(s, data[i = p]);
        }
        return i;
    }
};
#line 1 "cp-library/src/algebra/sum.hpp"
template < class T > class sum_monoid {
  public:
    using set = T;
    static constexpr T op(const T &l, const T &r) { return l + r; }
    static constexpr T id() { return T(0); }
    static constexpr T inv(const T &x) { return -x; }
    static constexpr T pow(const T &x, const ll n) { return x * n; }
    static constexpr bool comm = true;
};
#line 5 "A.cpp"

int main() {
    int N = in();
    vector<i64> A = in(N);
    vector<i64> V = A;
    unique(V);
    auto ID = [&](int x) { return lower_bound(V, x); };
    const int nV = V.size();

    const i64 INF = 1e18;
    vector cost(N, vector(N, INF));
    for(int i : rep(N)) {
        fenwick_tree<sum_monoid<i64>> tree0(nV), tree1(nV);
        int sz = 0;
        for(int j : rep(i, N)) {
            const int p = ID(A[j]);
            sz++;
            tree0.add(p, +1);
            tree1.add(p, A[j]);
            
            const int m = tree0.search([&](int x) { return 2 * x >= sz; });
            cost[i][j] = 0;
            cost[i][j] += tree1.fold(m, nV) - V[m] * tree0.fold(m, nV);
            cost[i][j] += V[m] * tree0.fold( 0, m) - tree1.fold( 0, m);
        }
    }

    vector dp(N, INF);
    dp[0] = 0;
    for(int i : rep(N)) {
        for(int j : rep(N)) if(i <= j) chmin(dp[j], dp[i] + cost[i][j]);
    }
    print(dp[N - 1]);
}
accuracy: 1
time_ms: 400
memory_kb: 73500
final_rank: 14

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 2 "cp-library/src/data_structure/fenwick_tree.hpp"

template < class comm_monoid > class fenwick_tree {
  public:
    using T = typename comm_monoid::set;

  private:
    int n, n2;
    vector< T > data;

    int ceil_pow2(int n) {
        int x = 1;
        while(x < n) x <<= 1;
        return x;
    }

  public:
    fenwick_tree() : fenwick_tree(0) {}
    fenwick_tree(int n) : n(n), n2(ceil_pow2(n)), data(n + 1, comm_monoid::id()) { assert(comm_monoid::comm); }
    fenwick_tree(const vector< T > &a) : n(a.size()), n2(ceil_pow2(n)), data(a) {
        assert(comm_monoid::comm);
        data.insert(data.begin(), {comm_monoid::id()});
        for(int i = 1; i <= n; i++) {
            int p = i + (i & -i);
            if(p <= n) data[p] = comm_monoid::op(data[i], data[p]);
        }
    }

    void add(int i, T x) {
        for(int p = i + 1; p <= n; p += p & -p) data[p] = comm_monoid::op(data[p], x);
    }
    // [0, r)
    T fold(int r) {
        T s = comm_monoid::id();
        for(int p = r; p > 0; p -= p & -p) s = comm_monoid::op(data[p], s);
        return s;
    }
    // [l, r)
    T fold(int l, int r) {
        return comm_monoid::op(comm_monoid::inv(fold(l)), fold(r));
    }
    T get(int i) {
        return fold(i, i + 1);
    }
    void set(int i, T x) {
        add(i, comm_monoid::op(comm_monoid::inv(get(i)), x));
    }
    template< class func > int search(const func &f) {
        T s = comm_monoid::id();
        if(f(s)) return 0;
        int i = 0, k = n2;
        while(k >>= 1) {
            int p = i | k;
            if(p <= n && !f(comm_monoid::op(s, data[p]))) s = comm_monoid::op(s, data[i = p]);
        }
        return i;
    }
};
#line 1 "cp-library/src/algebra/sum.hpp"
template < class T > class sum_monoid {
  public:
    using set = T;
    static constexpr T op(const T &l, const T &r) { return l + r; }
    static constexpr T id() { return T(0); }
    static constexpr T inv(const T &x) { return -x; }
    static constexpr T pow(const T &x, const ll n) { return x * n; }
    static constexpr bool comm = true;
};
#line 5 "A.cpp"

int main() {
    int N = in();
    vector<i64> A = in(N);
    vector<i64> V = A;
    unique(V);
    auto ID = [&](int x) { return lower_bound(V, x); };
    const int nV = V.size();

    const i64 INF = 1e18;
    vector cost(N, vector(N, INF));
    for(int i : rep(N)) {
        fenwick_tree<sum_monoid<i64>> tree0(nV), tree1(nV);
        int sz = 0;
        for(int j : rep(i, N)) {
            const int p = ID(A[j]);
            sz++;
            tree0.add(p, +1);
            tree1.add(p, A[j]);
            
            const int m = tree0.search([&](int x) { return 2 * x >= sz; });
            cost[i][j] = 0;
            cost[i][j] += tree1.fold(m, nV) - V[m] * tree0.fold(m, nV);
            cost[i][j] += V[m] * tree0.fold( 0, m) - tree1.fold( 0, m);
        }
    }

    vector dp(N, INF);
    dp[0] = 0;
    for(int i : rep(N)) {
        for(int j : rep(N)) if(i <= j) chmin(dp[j], dp[i] + cost[i][j]);
    }
    print(dp[N - 1]);
}
accuracy: 1
time_ms: 390
memory_kb: 73524
final_rank: 13

code_snippet: #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) { return (ull)rng() % B; }

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int n;
    cin >> n;
    vector<ll> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    vector<ll> dp(n, 1e18);
    dp[0] = 0;
    for (int i = 0; i < n; i++) {
        priority_queue<ll> A;
        priority_queue<ll, vector<ll>, greater<ll>> B;
        ll sa = 0, sb = 0;
        for (int j = i; j < n; j++) {
            A.push(a[j]);
            sa += a[j];
            if (A.size() and B.size() and A.top() > B.top()) {
                B.push(A.top());
                sb += A.top(), sa -= A.top();
                A.pop();
                A.push(B.top());
                sa += B.top(), sb -= B.top();
                B.pop();
            }
            if (A.size() >= B.size() + 2) {
                B.push(A.top());
                sb += A.top(), sa -= A.top();
                A.pop();
            }
            ll mid = A.top();
            ll cost = (mid * (A.size()) - sa) + (sb - mid * (B.size()));
            dp[j] = min(dp[j], dp[i] + cost);
        }
    }
    cout << dp[n - 1] << endl;
}
accuracy: 1
time_ms: 380
memory_kb: 3564
final_rank: 7

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
#define inf 1e9
#define INF 1e17
#define rep(i, n) for(int (i) = 0; (i) < (n); (i)++)
#define all(a) (a).begin(), (a).end()

int n;
vector<int> a;
ll dp[3010];
bool vis[3010];

ll solve(int now){
    if(vis[now])return dp[now];
    vis[now] = true;

    if(now == n - 1)return dp[now] = 0;

    ll res = INF;
    multiset<ll> B, S;
    ll sum_B = 0, sum_S = 0;
    B.insert(a[now]);
    sum_B += a[now];
    for(int nxt = now + 1; nxt < n; nxt++){
        auto ite1 = B.begin();
        ll m1 = *ite1;

        if(a[nxt] >= m1){
            B.insert(a[nxt]);
            sum_B += a[nxt];
        }
        else{
            S.insert(a[nxt]);
            sum_S += a[nxt];
        }

        ll sz_B = B.size(), sz_S = S.size();

        int mid = 0;
        if(sz_B == sz_S + 2){
            auto ite = B.begin();
            ll x = *ite;
            S.insert(x);
            sum_S += x;
            B.erase(B.find(x));
            sum_B -= x;
            mid = x;
        }
        else if(sz_B == sz_S + 1){
            auto ite = B.begin();
            mid = *ite;
        }
        else if(sz_B == sz_S){
            auto ite = B.begin();
            mid = *ite;
        }
        else if(sz_B + 1 == sz_S){
            auto ite = S.rbegin();
            mid = *ite;
        }
        else if(sz_B + 2 == sz_S){
            auto ite = S.rbegin();
            ll x = *ite;
            B.insert(x);
            sum_B += x;
            S.erase(S.find(x));
            sum_S -= x;
            mid = x;
        }

        sz_B = B.size();
        sz_S = S.size();

        ll tmp = sum_B - mid * sz_B + mid * sz_S - sum_S;
        res = min(res, tmp + solve(nxt));
    }
    return dp[now] = res;
}

int main(){
    cin >> n;
    a.resize(n);
    rep(i, n)cin >> a[i];
    ll ans = solve(0);
    cout << ans << endl;
}
accuracy: 1
time_ms: 490
memory_kb: 4360
final_rank: 9

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, l, r) for (int i = (l); i < r; ++i)
#define rrep(i, l, r) for (int i = (r - 1); i >= l; --i)
#define all(c) begin(c), end(c)

#ifdef LOCAL
#define debug(...) debug_impl(#__VA_ARGS__, __VA_ARGS__)
template <class H, class... Ts> void debug_impl(string s, H&& h, Ts &&... ts) {
  cerr << '(' << s << "): (" << forward<H>(h);
  ((cerr << ", " << forward<Ts>(ts)), ..., (cerr << "\n"));
}
#else
#define debug(...) void(0)
#endif

template <class T> bool chmax(T& a, const T& b) {
  return b > a ? (a = b, true) : false;
}
template <class T> bool chmin(T& a, const T& b) {
  return b < a ? (a = b, true) : false;
}

template <class T> istream& operator>>(istream& in, vector<T>& v) {
  for (auto& e : v) in >> e;
  return in;
}
template <class ... Args> void read(Args &... args) {
  (cin >> ... >> args);
}
template <class T> ostream& operator<<(ostream& out, const vector<T>& v) {
  int n = v.size();
  rep(i, 0, n) {
    out << v[i];
    if (i + 1 != n) out << ' ';
  }
  return out;
}
template <class H, class ... Ts> void print(H&& h, Ts &&...ts) {
  cout << h, ((cout << " " << forward<Ts>(ts)), ..., (cout << "\n"));
}

struct io_setup_ {
  io_setup_() {
    ios::sync_with_stdio(false), cin.tie(nullptr);
    cout << fixed << setprecision(10);
    cerr << fixed << setprecision(10);
  }
} io_setup{};

using ll = long long;

const ll INF = 1LL<<60;

template <class T> using vc = vector<T>;
template <class T> using vvc = vector<vc<T>>;

template <class T> using pqg = priority_queue<T, vector<T>, greater<T>>;

int main() {
    int n; read(n);
    vc<ll> a(n); 
    rep(i, 0, n) {
        read(a[i]);
    }
    vc<ll> dp(n + 1, INF);
    dp[0] = 0;
    rep(i, 0, n) {
        priority_queue<ll> lpque;
        pqg<ll> rpque;
        ll lsum = 0, rsum = 0;
        int cnt = 0;
        rep(j, i, n) {
            if(lpque.size() and lpque.top() < a[j]) {
                rpque.push(a[j]); rsum += a[j];
            } else {
                lpque.push(a[j]); lsum += a[j];
            }
            ++ cnt;
            while((int)lpque.size() > (cnt + 1) / 2) {
                rsum += lpque.top(), lsum -= lpque.top();
                rpque.push(lpque.top());
                lpque.pop();
            }
            while((int)rpque.size() > cnt - (cnt + 1) / 2) {
                lsum += rpque.top(), rsum -= rpque.top();
                lpque.push(rpque.top());
                rpque.pop();
            }
            if(cnt >= 2) {
                int sz = (int)lpque.size();
                debug(sz);
                ll cost = lpque.top() * sz - lsum + rsum - lpque.top() * (cnt - sz);
                debug(i, j, cnt, sz, lpque.top(), cost);
                debug(lsum, rsum);
                chmin(dp[j], dp[i] + cost);
            }
        }
    }
    print(dp[n - 1]);
}
accuracy: 1
time_ms: 150
memory_kb: 3616
final_rank: 2

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
#define inf 1e9
#define INF 1e17
#define rep(i, n) for(int (i) = 0; (i) < (n); (i)++)
#define all(a) (a).begin(), (a).end()

int n;
vector<int> a;
ll dp[3010];
bool vis[3010];

ll solve(int now){
    if(vis[now])return dp[now];
    vis[now] = true;

    if(now == n - 1)return dp[now] = 0;

    ll res = INF;
    multiset<int> B, S;
    ll sum_B = 0, sum_S = 0;
    B.insert(a[now]);
    sum_B += a[now];
    for(int nxt = now + 1; nxt < n; nxt++){
        auto ite1 = B.begin();
        int m1 = *ite1;

        if(a[nxt] >= m1){
            B.insert(a[nxt]);
            sum_B += a[nxt];
        }
        else{
            S.insert(a[nxt]);
            sum_S += a[nxt];
        }

        int sz_B = B.size(), sz_S = S.size();

        int mid = 0;
        if(sz_B == sz_S + 2){
            auto ite = B.begin();
            int x = *ite;
            S.insert(x);
            sum_S += x;
            B.erase(B.find(x));
            sum_B -= x;
            mid = x;
        }
        else if(sz_B == sz_S + 1){
            auto ite = B.begin();
            mid = *ite;
        }
        else if(sz_B == sz_S){
            auto ite = B.begin();
            mid = *ite;
        }
        else if(sz_B + 1 == sz_S){
            auto ite = S.rbegin();
            mid = *ite;
        }
        else if(sz_B + 2 == sz_S){
            auto ite = S.rbegin();
            int x = *ite;
            B.insert(x);
            sum_B += x;
            S.erase(S.find(x));
            sum_S -= x;
            mid = x;
        }

        sz_B = B.size();
        sz_S = S.size();

        ll tmp = sum_B - mid * sz_B + mid * sz_S - sum_S;
        res = min(res, tmp + solve(nxt));
    }
    return dp[now] = res;
}

int main(){
    cin >> n;
    a.resize(n);
    rep(i, n)cin >> a[i];
    ll ans = solve(0);
    cout << ans << endl;
}
accuracy: 0.047619047619047616
time_ms: 270
memory_kb: 4208
final_rank: 19

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
#define inf 1e9
#define INF 1e17
#define rep(i, n) for(int (i) = 0; (i) < (n); (i)++)
#define all(a) (a).begin(), (a).end()

int n;
vector<int> a;
ll dp[3010];
bool vis[3010];

ll solve(int now){
    if(vis[now])return dp[now];
    vis[now] = true;

    if(now == n - 1)return dp[now] = 0;

    ll res = INF;
    multiset<int> B, S;
    ll sum_B = 0, sum_S = 0;
    B.insert(a[now]);
    sum_B += a[now];
    for(int nxt = now + 1; nxt < n; nxt++){
        auto ite1 = B.begin();
        int m1 = *ite1;

        if(a[nxt] >= m1){
            B.insert(a[nxt]);
            sum_B += a[nxt];
        }
        else{
            S.insert(a[nxt]);
            sum_S += a[nxt];
        }

        int sz_B = B.size(), sz_S = S.size();

        int mid = 0;
        if(sz_B == sz_S + 2){
            auto ite = B.begin();
            int x = *ite;
            S.insert(x);
            sum_S += x;
            B.erase(B.find(x));
            sum_B -= x;
            mid = x;
        }
        else if(sz_B == sz_S + 1){
            auto ite = B.begin();
            mid = *ite;
        }
        else if(sz_B == sz_S){
            auto ite = B.begin();
            mid = *ite;
        }
        else if(sz_B + 1 == sz_S){
            auto ite = S.rbegin();
            mid = *ite;
        }
        else if(sz_B + 2 == sz_S){
            auto ite = S.rbegin();
            int x = *ite;
            B.insert(x);
            sum_B += x;
            S.erase(S.find(x));
            sum_S -= x;
            mid = x;
        }

        sz_B = B.size();
        sz_S = S.size();

        ll tmp = sum_B - mid * sz_B + mid * sz_S - sum_S;
        res = min(res, tmp + solve(nxt));
    }
    return dp[now] = res;
}

int main(){
    cin >> n;
    a.resize(n);
    rep(i, n)cin >> a[i];
    int ans = solve(0);
    cout << ans << endl;
}
accuracy: 0.047619047619047616
time_ms: 270
memory_kb: 4208
final_rank: 19

code_snippet: /* -*- coding: utf-8 -*-
 *
 * 3219.cc: Warp Points
 */

#include<cstdio>
#include<set>
#include<algorithm>
#include<functional>
 
using namespace std;

/* constant */

const int MAX_N = 3000;
const long long LINF = 1LL << 62;

/* typedef */

typedef long long ll;
typedef multiset<int,greater<int> > msig;
typedef multiset<int> msi;

/* global variables */

int as[MAX_N];
ll rcs[MAX_N][MAX_N], dp[MAX_N];

/* subroutines */

void gins(msig &g0, msi &g1, ll &s0, ll &s1, int a) {
  if (g0.empty() || a <= *g0.begin()) g0.insert(a), s0 += a;
  else g1.insert(a), s1 += a;

  if (g0.size() > g1.size() + 1) {
    int b = *g0.begin();
    g0.erase(g0.begin()), s0 -= b;
    g1.insert(b), s1 += b;
  }
  else if (g0.size() < g1.size()) {
    int b = *g1.begin();
    g1.erase(g1.begin()), s1 -= b;
    g0.insert(b), s0 += b;
  }
}

ll cost(msig &g0, msi &g1, ll &s0, ll &s1) {
  if (g0.empty()) return 0;
  int a = *g0.begin();
  return ((ll)a * g0.size() - s0) + (s1 - (ll)a * g1.size());
}

/* main */

int main() {
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) scanf("%d", as + i);

  for (int i = 0; i < n; i++) {
    ll s0 = 0, s1 = 0;
    msig g0;
    msi g1;
    for (int j = i; j < n; j++) {
      gins(g0, g1, s0, s1, as[j]);
      rcs[i][j] = cost(g0, g1, s0, s1);
      //printf("rcs[%d][%d] = %lld\n", i, j, rcs[i][j]);
    }
  }

  fill(dp, dp + n, LINF);
  dp[0] = 0;

  for (int i = 0; i < n; i++)
    for (int j = i + 1; j < n; j++)
      dp[j] = min(dp[j], dp[i] + rcs[i][j]);

  printf("%lld\n", dp[n - 1]);

  return 0;
}
accuracy: 1
time_ms: 460
memory_kb: 72888
final_rank: 15

code_snippet: #include<cstdio>
#include<queue>
#include<vector>
using namespace std;
#define Maxn 3010
#define INF (1ll<<60)

int n;
long long a[Maxn], Cost[Maxn][Maxn], f[Maxn];

int main()
{
    scanf("%d", &n);
    for (int i=1; i<=n; i++) scanf("%lld", &a[i]);
    for (int i=1; i<=n; i++)
    {
        Cost[i][i] = 0;
        long long Min_cost = 0, Max_cost = 0;
        priority_queue<long long> Min_queue;
        priority_queue<long long, vector<long long>, greater<long long>> Max_queue;
        for (int j=i; j<=n; j++)
        {
            if ((Max_queue.empty()) || (a[j] >= Max_queue.top()))
            {
                Max_queue.push(a[j]);
                Max_cost += a[j];
                Max_queue.push(a[j]);
                Max_cost += a[j];
                
                Min_cost += Max_queue.top();
                Min_queue.push(Max_queue.top());
                
                Max_cost -= Max_queue.top();
                Max_queue.pop();
            }
            else
            {
                Min_queue.push(a[j]);
                Min_cost += a[j];
                Min_queue.push(a[j]);
                Min_cost += a[j];
                
                Max_cost += Min_queue.top();
                Max_queue.push(Min_queue.top());
                
                Min_cost -= Min_queue.top();
                Min_queue.pop();
            }
            
            long long m = Max_queue.top();
            Cost[i][j] = ((Max_cost - m * Max_queue.size()) + (m * Min_queue.size() - Min_cost)) / 2;
            // printf("%d %d %lld\n", i, j, Cost[i][j]);
        }
    }

    for (int i=1; i<=n; i++) f[i] = INF; f[1] = 0;
    for (int i=2; i<=n; i++)
        for (int j=1; j<i; j++)
            f[i] = min(f[i], f[j] + Cost[j][i]);
    
    printf("%lld\n", f[n]);
}
accuracy: 1
time_ms: 270
memory_kb: 72836
final_rank: 12