Hide

Problem F
Juggler

As part of my magical juggling act, I am currently juggling a number of objects in a circular path with one hand. However, as my rather elaborate act ends, I wish to drop all of the objects in a specific order, in a minimal amount of time. On each move, I can either rotate all of the objects counterclockwise by one, clockwise by one, or drop the object currently in my hand. If I drop the object currently in my hand, the next object (clockwise) will fall into my hand. What’s the minimum number of moves it takes to drop all of the balls I’m juggling?

Input

There will be a single test case in the input. This test case begins with an integer $n$, ($1 \le n \le 100\, 000$) on its own line, indicating the total number of balls begin juggled. Each of the next $n$ lines consists of a single integer, $k_ i$ ($1 \le k_ i \le n$), which describes a single ball: $i$ is the position of the ball starting clockwise from the juggler’s hand, and $k_ i$ is the order in which the ball should be dropped. The set of numbers $\{ k_1, k_2, \ldots , k_ n\} $ is guaranteed to be a permutation of the numbers $1 \ldots n$.

Output

Output a single integer on its own line, indicating the minimum number of moves I need to drop all of the balls in the desired order. All possible inputs yield answers which will fit in a signed $64$-bit integer.

Sample Input Explanation

The first ball is in the juggler’s hand and should be dropped third; the second ball is immediately clockwise from the first ball and should be dropped second; the third ball is immediately clockwise from the second ball and should be dropped first.

Sample Input 1 Sample Output 1
3
3
2
1
5

Please log in to submit a solution to this problem

Log in