Overtakes on the Ring Road
The Ring Road Grand Prix is run by n cars. Each car is known by its grid slot: the car that starts from slot 1 (pole position) is car 1, the car right behind it is car 2, and so on down to car n at the back of the grid. So when the lights go out, the running order from the front is 1, 2, …, n.
The race is a long one, but it follows strict rules:
- The cars always form a single file, so at every moment there is a well-defined running order from first to last place. Nobody is ever lapped and nobody retires: all
ncars finish. - The running order changes only through overtakes. An overtake involves two cars that are right next to each other in the running order: the car behind passes the car directly in front of it, and the two swap places. Every other car keeps its place. Overtakes happen one at a time.
- No grudges are settled twice: once car
ahas overtaken carb, carbnever overtakes carafor the rest of the race. (Caramay overtake many other cars, and other cars may overtake cara.)
You were not watching the race. You only have the official result: the finishing order from the winner to the last car. Find how many overtakes took place during the race. Under the rules above this number is the same for every race that ends in that order.
Input
The first line contains an integer n (1 ≤ n ≤ 2·10^5), the number of cars.
The second line contains n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n): p_i is the grid slot of the car that finished in place i. So p_1 is the winner and p_n finished last.
Output
Print a single integer: the number of overtakes during the race.
Notes
In the first example car 3 finished ahead of cars 1 and 2, so it overtook each of them once, and car 5 overtook car 4. That is 3 overtakes. One possible race: 3 passes 2, then 3 passes 1, then 5 passes 4.
In the second example the race could have gone like this (running order after each overtake):
start 1 2 3 4 5 6
2 passes 1 2 1 3 4 5 6
6 passes 5 2 1 3 4 6 5
6 passes 4 2 1 3 6 4 5
6 passes 3 2 1 6 3 4 5
6 passes 1 2 6 1 3 4 5
5 passes 4 2 6 1 3 5 4
5 passes 3 2 6 1 5 3 4
That is 7 overtakes, and no race following the rules can end in this order with a different number.
The answer can be as large as about 2·10^10, which does not fit in a 32-bit integer.