Birthday
Time limit2sMemory limit64 MB
Children sit around a round table in order 1..n; reseat them into a given cyclic order while minimizing the largest distance anyone walks along the circle.
- Level
Hard8 of 10
- Topics
- Binary search, Sorting, Math, Implementation
- Solved
- No attempts yet
Problem
It is Byteman's birthday today. There are children at his birthday party (Byteman included), numbered from to . Byteman's parents have prepared a big round table with chairs around it.
The children sit down in order. Child takes any seat. Child takes the seat to the left, child the next seat to the left, and so on, until child takes the last free seat, between child and child .
Some children get noisy when they sit too close to certain others, so the parents want to reseat everyone into a specific cyclic order given by a permutation (distinct integers from to ): child must sit between and , child (for ) must sit between and , and child must sit between and . Note that child may end up on either side of child : the cyclic order can be realized in either rotational direction.
To reach the desired order, every child moves around the table some number of seats, either to the left or to the right; the parents choose a direction and a distance for each child. On a signal, all children stand up at once, walk to their new places, and sit down.
The mess of a reseating is the largest number of seats moved by any single child. Among all reseatings that produce the desired cyclic order, the parents want one with the smallest possible mess.
Write a program that reads and the target permutation and prints the minimum possible mess.
Input
The first line contains one integer ().
The second line contains integers separated by single spaces, forming a permutation of that describes the desired cyclic order of the children.
Output
Print a single integer: the minimum possible mess.
Hint

For and the target order , the left figure shows the initial seating. In one optimal reseating (middle figure), children and move one seat, children and move two seats, and children and stay put. The required order then holds: sits between and , between and , between and , between and , between and , and between and . Another optimal seating is shown on the right. In both, no child moves more than two seats, so the minimum mess is .