Out of Sorts (Platinum)#10390

Out of Sorts (Platinum)

1 second
128 megabytes
Very hard

Keeping an eye on long-term career opportunities beyond the farm, Bessie the cow has started learning algorithms on various online coding websites. Her two favorite algorithms are "bubble sort" and "quicksort", but unfortunately, Bessie easily confuses them and ends up implementing a rather odd hybrid of the two!

Let us call the position between elements and i + 1 of an array a partition point if the maximum of A_0, \ldots, A_i is not larger than the minimum of A_{i+1}, \ldots, A_{n-1}. Bessie remembers that quicksort rearranges an array so that it has a partition point and then recursively sorts the two parts A_0, \ldots, A_i and A_{i+1}, \ldots, A_{n-1}. However, although she correctly notes that all partition points of an array can be found in linear time, she has forgotten how quicksort is supposed to rearrange the array to quickly create a partition point! In what may prove to be the worst algorithmic blunder in the history of sorting, she makes the unfortunate decision to use bubble sort for this task.

Here is an outline of Bessie's implementation for sorting an array . First, she writes a simple function that performs one pass of bubble sort:

bubble_sort_pass (A) {
   for i = 0 to length(A)-2
      if A[i] > A[i+1], swap A[i] and A[i+1]
}

The recursive code of her quick(ish) sort function is structured as follows:

quickish_sort (A) {
   if length(A) = 1, return
   do { // Main loop
      work_counter = work_counter + length(A)
      bubble_sort_pass(A)
   } while (no partition points exist in A)
   divide A at all partition points; recursively quickish_sort each piece
}

Bessie is curious how fast her code will run. For simplicity, she assumes that each iteration of the main loop takes linear time, so she increases the global variable work\_counter inside the loop accordingly to keep track of the total work done by the algorithm.

Given the input array, predict the final value of work\_counter after the array is sorted by quickish\_sort.

Input

The first line contains an integer n~(1 \le n \le 10^5). Each of the next lines contains one element of the array A_0, \ldots, A_{n-1} — an integer from to 10^9. The elements are not necessarily distinct.

Output

Print a single integer — the final value of work\_counter.

Examples

Example 1

Loading
Loading

Note

In this example, we start with the array 20\ 2\ 3\ 4\ 9\ 8\ 7. After one pass of bubble sort (which adds to work\_counter), we get 2 \mid 3 \mid 4 \mid 9\ 8\ 7 \mid 20, where denotes a partition point. Therefore, the problem is divided into recursive subproblems: sorting , , , and (each requiring zero work) and sorting . For the subproblem , one iteration of the main loop ( units of work) yields 8\ 7 \mid 9, after which a final pass over ( units of work) completes the sort. In total, work\_counter equals 7 + 3 + 2 = 12.