#K43877. Minimum Operations to Sort Cards
Minimum Operations to Sort Cards
Minimum Operations to Sort Cards
You are given several test cases. Each test case consists of a sequence of distinct integers representing the order of cards. Your task is to determine the minimum number of operations required to sort each sequence into non-decreasing order under the following rules:
- If the sequence is already sorted in non-decreasing (ascending) order, 0 operations are needed.
- If the sequence is sorted in strictly decreasing order, 1 operation is needed (for example, by reversing the sequence).
- Otherwise, 2 operations are sufficient to sort the sequence.
In mathematical terms, let \(A = [a_1, a_2, \dots, a_n]\). Then the answer \(ans\) for a given test case can be defined as:
\[ ans = \begin{cases} 0, & \text{if } A = \text{sorted}(A) \\[6pt] 1, & \text{if } A = \text{reverse}(\text{sorted}(A)) \\[6pt] 2, & \text{otherwise} \end{cases} \]Apply this procedure on each test case independently.
inputFormat
The input is read from standard input (stdin). The first line contains an integer \(T\) representing the number of test cases. Each test case consists of two lines:
- The first line contains an integer \(n\), the number of cards.
- The second line contains \(n\) space-separated integers representing the cards.
outputFormat
For each test case, output the minimum number of operations on a separate line to transform the sequence into non-decreasing order. The output is written to standard output (stdout).
## sample3
4
4 3 2 1
5
3 1 4 2 5
3
1 2 3
1
2
0
</p>