E. Complexity of Quicksort
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

In the city of Shanghai, the young programmer Kai seeks the wisdom of his mentor, Master Wei. One day, Master Wei presented Kai with a challenge on algorithm analysis, a fundamental lesson to achieve mastery.

"Little Kai," said the Master, "a programmer's strength lies not in writing code, but in understanding it deeply. Observe this scroll. It describes the 'Wise Partitioning Method', a way of sorting sequences."

On the scroll was an algorithm, which coincidentally looks very much like an implementation of Quicksort in Python:

cmps = 0
def quicksort(A, l, r):
if r <= l:
return
# The Master chooses the middle element as a guide
m = (l + r) // 2
k = pivot(A, l, r, A[m])
quicksort(A, l, k - 1)
quicksort(A, k + 1, r)


def pivot(A, l, r, x):
# Each element is compared with the guide x
for y in A[l : r + 1]:
cmps += 1
if y < x:
A[l] = y
l += 1
elif y > x:
A[r] = y
r -= 1
A[l] = x
return l

The function $$$pivot(A,l,r,x)$$$ rearranges the values in the segment $$$A[l..r]$$$ as follows: values smaller than $$$x$$$ are moved to $$$A[l..k-1]$$$ (in the same relative order), values larger than $$$x$$$ are moved to $$$A[k+1..r]$$$ (in the reverse relative order), and the guide value $$$x$$$ is placed at $$$A[k]$$$.

Master Wei then handed Kai a sequence of numbers representing the energy levels of a sleeping dragon. "A hasty apprentice would try to run this code to get the answer. But a true master can predict the cost without executing a single line."

"Your task, Kai," the Master concluded, "is to tell me the exact cost of the method for this sequence. Calculate the final value of the cost variable $$$cmps$$$ that would be obtained at the end of the $$$quicksort(A, 0, n-1)$$$ call. This is your lesson for today."

Input

The first line contains an integer $$$N$$$ ($$$1 \leq N \leq 2 \cdot 10^5$$$), the size of the array. The second line contains $$$N$$$ integers $$$A[0], \ldots, A[N-1]$$$ ($$$|A[i]| \leq 10^9$$$), the elements of the array. All elements of $$$A$$$ are distinct.

Output

A single integer, the total number of comparisons that Master Wei's method will perform.

Examples
Input
1
5
Output
0
Input
10
9 8 7 6 5 4 3 2 1 0
Output
25
Input
10
1 3 5 7 9 8 6 4 2 0
Output
54
Input
5
5 45 2 12 21
Output
11