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: Accepted)

#include <bits/stdc++.h>
using namespace std;

const int N = 200005;
const int INF = 2e9;

int n, a[N];
vector <int> z;
pair<int,int> T[N << 2];
int lz[N << 2]; // the amount of adding

#define mid ((l + r) >> 1)

void build(int v, int l, int r) {
	if (l == r) { T[v] = {z[l - 1], l}; return; }
	build(v << 1, l, mid);
	build(v << 1 | 1, mid + 1, r);
	T[v] = min(T[v << 1], T[v << 1 | 1]);
}

void push(int v, int l, int r) {
	if (lz[v] == 0) return;
	if (l < r) lz[v << 1] += lz[v], lz[v << 1 | 1] += lz[v];
	T[v].first += lz[v];
	lz[v] = 0;
}

void upd(int v, int l, int r, int L, int R, int val) {
	push(v, l, r);
	if (R < l || L > r) return;
	if (L <= l && r <= R) {
		lz[v] = val; push(v, l, r); return;
	}
	upd(v << 1, l, mid, L, R, val);
	upd(v << 1 | 1, mid + 1, r, L, R, val);
	T[v] = min(T[v << 1], T[v << 1 | 1]);
}

pair<int,int> get(int v, int l, int r, int L, int R) {
	push(v, l, r);
	if (R < l || L > r) return {INF, 0};
	if (L <= l && r <= R) return T[v];
	return min(get(v << 1, l, mid, L, R), get(v << 1 | 1, mid + 1, r, L, R));
}

#undef mid

int main() {
	ios_base::sync_with_stdio(false); cin.tie(0);
	cin >> n;
	for (int i = 1; i <= n; ++i) {
		cin >> a[i];
		z.push_back(a[i]);
	}
	sort(z.begin(), z.end());
	z.erase(unique(z.begin(), z.end()), z.end());

	build(1, 1, z.size());

	long long res = 0; // result
	for (int i = 1; i <= n; ++i) {
		int p = lower_bound(z.begin(), z.end(), a[i]) - z.begin() + 1;
		pair<int, int> w = get(1, 1, z.size(), p, z.size()); // get min cost

		int wcost = w.first;
		int	wpos = w.second;

		res += wcost - a[i];

		upd(1, 1, z.size(), 1, wpos - 1, +1);
	}

	cout << res << endl;
}