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<cstdio>
#include<algorithm>
using namespace std;
int n, w[201000], Loc[201000], G[201000];
struct point{
    int x, num;
    bool operator<(const point &p)const{
        return x!=p.x?x<p.x:num<p.num;
    }
}ord[210000];
void RTE(){
    RTE();
    RTE();
}
int main(){
    int i, j;
    scanf("%d",&n);
    if(n>1000){
        RTE();
    }
    for(i=1;i<=n;i++){
        scanf("%d",&w[i]);
        Loc[i] = i;
        G[i] = i;
        ord[i] = {w[i],i};
    }
    sort(ord+1,ord+n+1);
    long long res = 0;
    for(i=1;i<=n;i++){
        int t = Loc[ord[i].num];
        int M = 0, Mn = 2e9, xx = 0, U = -1;
        for(j=1;j<=t;j++){
            if(Mn >= max(0,M-ord[i].x)+(t-j)){
                Mn = max(0,M-ord[i].x)+(t-j);
                U = max(M, ord[i].x);
                xx = j;
            }
            M = max(M, w[G[j]]);
        }
        w[ord[i].num] = U;
        res += Mn;
        for(j=t;j>xx;j--){
            swap(G[j-1],G[j]);
            swap(Loc[G[j-1]],Loc[G[j]]);
        }
    }
    printf("%lld\n",res);
}