atcoder#AGC014F. [AGC014F] Strange Sorting

[AGC014F] Strange Sorting

Score : 24002400 points

Problem Statement

Takahashi loves sorting.

He has a permutation (p1,p2,...,pN)(p_1,p_2,...,p_N) of the integers from 11 through NN. Now, he will repeat the following operation until the permutation becomes (1,2,...,N)(1,2,...,N):

  • First, we will define high and low elements in the permutation, as follows. The ii-th element in the permutation is high if the maximum element between the 11-st and ii-th elements, inclusive, is the ii-th element itself, and otherwise the ii-th element is low.
  • Then, let a1,a2,...,aka_1,a_2,...,a_k be the values of the high elements, and b1,b2,...,bNkb_1,b_2,...,b_{N-k} be the values of the low elements in the current permutation, in the order they appear in it.
  • Lastly, rearrange the permutation into (b1,b2,...,bNk,a1,a2,...,ak)(b_1,b_2,...,b_{N-k},a_1,a_2,...,a_k).

How many operations are necessary until the permutation is sorted?

Constraints

  • 1N2×1051 \leq N \leq 2 \times 10^5
  • (p1,p2,...,pN)(p_1,p_2,...,p_N) is a permutation of the integers from 11 through NN.

Input

Input is given from Standard Input in the following format:

NN

p1p_1 p2p_2 ... pNp_N

Output

Print the number of operations that are necessary until the permutation is sorted.

5
3 5 1 2 4
3

The initial permutation is (3,5,1,2,4)(3,5,1,2,4), and each operation changes it as follows:

  • In the first operation, the 11-st and 22-nd elements are high, and the 33-rd, 44-th and 55-th are low. The permutation becomes: (1,2,4,3,5)(1,2,4,3,5).
  • In the second operation, the 11-st, 22-nd, 33-rd and 55-th elements are high, and the 44-th is low. The permutation becomes: (3,1,2,4,5)(3,1,2,4,5).
  • In the third operation, the 11-st, 44-th and 55-th elements are high, and the 22-nd and 33-rd and 55-th are low. The permutation becomes: (1,2,3,4,5)(1,2,3,4,5).
5
5 4 3 2 1
4
10
2 10 5 7 3 6 4 9 8 1
6