#C6153. Minimum Operations to Sort Deck

    ID: 49882 Type: Default 1000ms 256MiB

Minimum Operations to Sort Deck

Minimum Operations to Sort Deck

You are given a deck of cards represented as a sequence of unique integers. Your task is to determine the minimum number of operations required to sort the deck in increasing order. In one operation, you can reverse a contiguous segment of the deck. The special observation is that if the deck is already sorted, no operation is needed. Otherwise, the number of operations required is equal to the number of segments where the order is strictly decreasing.

Mathematically, given a permutation \(\pi = [a_1, a_2, \dots, a_N]\), you need to compute the minimum number of reversals such that after performing these operations, the sequence is sorted in increasing order:

[ \min; { k : \text{reversal operations transforming } \pi \text{ into } [1,2,\ldots,N] } ]

Example 1: For the deck [4, 3, 2, 1], only one reversal (reversing the entire deck) is enough, so the answer is 1.

Example 2: For the deck [3, 5, 1, 4, 2], the optimal strategy requires 2 reversals, so the answer is 2.

inputFormat

The input is given via standard input (stdin) with the following format:

  • The first line contains an integer \(T\) denoting the number of test cases.
  • For each test case:
    • The first line contains an integer \(N\) denoting the number of cards in the deck.
    • The second line contains \(N\) space-separated integers representing the order of the cards.

outputFormat

For each test case, output a single integer on a new line representing the minimum number of reversal operations needed to sort the deck in increasing order.

## sample
1
4
4 3 2 1
1

</p>