eolymp
bolt
Спробуйте наш новий інтерфейс для відправки розв'язків

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? \InputFile There will be several test cases in the input. Each test case begins with an integer \textbf{n}, (\textbf{1} ≤ \textbf{n} ≤ \textbf{100000}) on its own line, indicating the total number of balls begin juggled. Each of the next \textbf{n} lines consists of a single integer, \textbf{k_i} (\textbf{1} ≤ \textbf{k_i} ≤ \textbf{n}), which describes a single ball: \textbf{i} is the position of the ball starting clockwise from the juggler’s hand, and \textbf{k_i} is the order in which the ball should be dropped. The set of numbers \{\textbf{k_1}, \textbf{k_2}, …, \textbf{k_n}\} is guaranteed to be a permutation of the numbers \textbf{1..n}. The input will terminate with a line containing a single \textbf{0}. \OutputFile For each test case, output a single integer on its own line, indicating the minimum number of moves \textbf{I} need to drop all of the balls in the desired order. Output no extra spaces, and do not separate answers with blank lines. All possible inputs yield answers which will fit in a signed \textbf{64}-bit integer. \textit{\textbf{Explanation of the sample input}}: 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 last.
Ліміт часу 3 секунди
Ліміт використання пам'яті 32 MiB
Вхідні дані #1
3
3
2
1
0
Вихідні дані #1
5
Джерело The University of Chicago Invitational Programming Contest 2012 15 April 2012