#P5846. [IOI 2005] bir

[IOI 2005] bir

Description

Today is Byteman’s birthday. There are nn children at his birthday party (including Byteman). The children are numbered from 11 to nn. Byteman’s parents prepared a big round table and placed nn chairs around it. When the children arrive, they sit down as follows: child 11 sits on some chair, then child 22 sits to the left of child 11, then child 33 sits to the left of child 22, and so on. Finally, child nn sits on the last empty chair, i.e. between child n1n-1 and child 11.

Byteman’s parents know the children very well, and they know that if some children sit next to each other, they will be very noisy. Therefore, they will rearrange the children’s seats in a specific order. This order is given by a permutation p1,p2,,pnp_1,p_2,\cdots,p_n (p1,p2,,pnp_1,p_2,\cdots,p_n are integers from 11 to nn). Child p1p_1 will sit between p2p_2 and pnp_n, child pip_i (i=2,3,,n1i = 2,3,\ldots,n-1) will sit between children pi1p_{i-1} and pi+1p_{i+1}, and child pnp_n will sit between children pn1p_{n-1} and p1p_1. Note that p1p_1 may sit either to the left of pnp_n or to the right of pnp_n.

To make all children sit in the given order, Byteman’s parents must let each child move some seats to the left or to the right around the table. They must decide how each child moves, that is, they must decide a direction and a distance. For a given moving instruction, all children stand up at once and move to their target seats and sit down. This process makes the party messy. The messiness is defined as the maximum moving distance among all children. Since the children can move in many different ways, Byteman’s parents will choose the one that minimizes the messiness. Help them find such a plan.

Your task is to write a program that reads from standard input the number of children and the permutation describing the target order, and computes the minimum possible messiness.

Input Format

The first line contains an integer nn (1n1061 \le n \le 10^6).

The second line contains nn integers p1,p2,,pnp_1,p_2,\cdots,p_n, separated by single spaces. p1,p2,,pnp_1,p_2,\cdots,p_n is a permutation of the set {1,2,,n}\{1,2,\cdots,n\}, describing the target order.

Output Format

One line containing one integer: the minimum messiness.

6
3 4 5 1 2 6

2

Hint

For 50%50\% of the testdata, 1n10001 \le n \le 1000.

For 100%100\% of the testdata, 1n1061 \le n \le 10^6.

Translated by ChatGPT 5