Problem:
Score : 1500 points

Problem Statement

We have a sequence A of length N.

On this sequence, we can perform the following two kinds of operations:

Swap two adjacent elements.

Select one element, and increment it by 1.

We will repeatedly perform these operations so that A will be a non-decreasing sequence. Find the minimum required number of operations.

Constraints

1 ≤ N ≤ 200000

1 ≤ A_i ≤ 10^9

A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1
A_2
:
A_N

Output

Print the minimum number of operations required to turn A into a non-decreasing sequence.

Sample Input 1

5
4
1
8
8
7

Sample Output 1

2

We can turn A into a non-decreasing sequence in two operations:

Initially, A = \{4, 1, 8, 8, 7\}.

Swap the first two elements. Now, A = \{1, 4, 8, 8, 7\}.

Increment the last element by 1. Now, A = \{1, 4, 8, 8, 8\}.

Sample Input 2

20
8
2
9
7
4
6
7
9
7
4
7
4
4
3
6
2
3
4
4
9

Sample Output 2

62

Solution in C++14 (GCC 5.4.1) (judge verdict: Runtime Error)

#include <bits/stdc++.h>
using namespace std;
typedef long long lint;
typedef long double llf;
typedef pair<lint, lint> pi;
const int MAXN = 2005, N = MAXN;
const int mod = 1e9 + 7, inv2 = (mod + 1) / 2;
int dp[MAXN][3][MAXN], odp[3][MAXN], sz[MAXN];
vector<int> adj[N];
void sadd(int &x, int y) {
	x += y;
	while (x >= mod) x -= mod;
}
void dfs(int v, int p = -1) {
	dp[v][0][1] = 1;
	sz[v] = 1;
	for (int u : adj[v]) {
		if (u != p) {
			dfs(u, v);
			memcpy(odp, dp[v], sizeof dp[v]);
			memset(dp[v], 0, sizeof dp[v]);
			for (int dv = 0; dv <= 2; ++dv) {
				for (int du = 0; du <= 2; ++du) {
					for (int use = 0; use <= 1; ++use) {
						if (use == 1 && (du > 1 || dv > 1)) continue;
						for (int cv = 1; cv <= sz[v]; ++cv)
							for (int cu = 1; cu <= sz[u]; ++cu) {
								int ways = (use == 1 ? mod - 1 : 1);
								if (use) {
									if (du == 0 && dv == 0) 
										ways = (long long) ways * 2 % mod;
									if (du == 1 && dv == 1)
										ways = (long long) ways * inv2 % mod;
								}
								sadd(dp[v][dv + use][cv + cu - use], 
										odp[dv][cv] * (long long) dp[u][du][cu] % mod * ways % mod);
							}

					}
				}
			}
			sz[v] += sz[u];
		}
	}
	
}
int f[N], a[N];
int main(){
	int n;
	long long res = 0;
	cin >> n;
	for (int j = 0; j < n; ++j) cin >> a[j];
	for (int j = 0; j < n; ++j) {
		int best = 2e9;
		for (int i = j; i >= 0; --i) {
			if (max(i == 0 ? 0 : a[i - 1] - a[j], 0) + j - i < best
				)
			{
				best = max(i == 0 ? 0 : a[i - 1] - a[j], 0) + j - i;
			}
		}
		for (int i = j; i >= 0; --i) {
			if (max(i == 0 ? 0 : a[i - 1] - a[j], 0) + j - i == best
				)
			{
				for (int k = j; k > i; --k) {
					swap(a[k], a[k - 1]);
				}
				a[i] = max(a[i], (i == 0 ? 0 : a[i - 1]));
			}
		}
		res += best;
	}
	cout << res << endl;
}