This page is still under construction.

Parts of this page are still being built. What you see may change.

Shuffles

Time limit2sMemory limit256 MB

Summary
Given a permutation of 1 to n, find the fewest riffle shuffles that can turn the sorted deck into it.
Level

Medium7 of 10

Topics
Math, Array
Solved
No attempts yet

Problem

The most common way to shuffle a deck of cards is called the riffle shuffle, or dovetail shuffle. The deck is split into two stacks, and the two stacks are then interleaved into one deck. The deck can be split anywhere, and the two stacks can be interleaved in any way. Interleaving keeps the order of the cards inside each stack.

For example, take a deck of 10 distinct cards.

1 2 3 4 5 6 7 8 9 10

Split it after the sixth card, which gives these two stacks.

1 2 3 4 5 6
7 8 9 10

Interleaving them can produce this order.

1 2 7 3 8 9 4 5 10 6

Shuffle once more. Splitting after the third card gives these two stacks.

1 2 7
3 8 9 4 5 10 6

Interleaving them again can produce this order.

3 8 1 9 4 5 2 7 10 6

That is one order the deck can reach after 2 shuffles. Suppose there are nn distinct cards and they start out perfectly ordered as 1,2,3,…,n1, 2, 3, \dots, n. Given one ordering of the deck, find the smallest number of shuffles that could produce that ordering.

Input

Each input consists of a single test case. Your program may be run several times on different inputs. The first line holds one integer nn (1≤n≤1061 \le n \le 10^6), the number of cards in the deck. The second line holds nn distinct integers cc (1≤c≤n1 \le c \le n), separated by single spaces, giving an ordering of the nn cards. The values cc are always a permutation of the numbers 11 through nn.

Output

Print one line with one integer, the minimum number of shuffles that could produce the given ordering. Print no spaces.

Examples3

  1. Example 1

    Input
    10
    1 2 7 3 8 9 4 5 10 6
    
    Expected output
    1
    
  2. Example 2

    Input
    10
    3 8 1 9 4 5 2 7 10 6
    
    Expected output
    2
    
  3. Example 3

    Input
    8
    2 1 4 3 6 5 8 7
    
    Expected output
    3