You are given a permutation a
consisting of n numbers 1, 2, …, n (a permutation is an array in which each element from 1 to n
occurs exactly once).
You can perform the following operation: choose some subarray (contiguous subsegment) of a
and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.
For example, if a=[2,1,4,5,3]
and we want to apply the operation to the subarray a[2,4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a=[2,5,1,4,3] or, for example, a=[2,1,5,4,3]
.
Your task is to calculate the minimum number of operations described above to sort the permutation a
in ascending order.
Input
The first line contains a single integer t
(1≤t≤2000
) — the number of test cases.
The first line of the test case contains a single integer n
(3≤n≤50
) — the number of elements in the permutation.
The second line of the test case contains n
distinct integers from 1 to n — the given permutation a
.
Output
For each test case, output a single integer — the minimum number of operations described above to sort the array a
in ascending order.
Example
Input
Copy
3
4
1 3 2 4
3
1 2 3
5
2 1 4 5 3
Output
Copy
1
0
2
Note
In the explanations, a[i,j]
defines the subarray of a that starts from the i-th element and ends with the j
-th element.
In the first test case of the example, you can select the subarray a[2,3]
and swap the elements in it.
In the second test case of the example, the permutation is already sorted, so you don’t need to apply any operations.
In the third test case of the example, you can select the subarray a[3,5]
and reorder the elements in it so a becomes [2,1,3,4,5], and then select the subarray a[1,2] and swap the elements in it, so a becomes [1,2,3,4,5]
.
题意:给定一个1到n的乱序序列,一次操作可以重置任意相邻的一堆元素的顺序,但不能一次性重置所有元素顺序,问至少操作多少次可以把序列排成1到n的递增顺序。
思路:wa了n次,最终总结出这种题的原则:既然可以重置任意一堆元素,那么这属于可变权限,对与可变权限,一律使用最大权限(操作n - 1 个),这算是贪心吧。
那么先看1是否在a[1]处,如果是,那么只需要看后面的元素是否各就各位,如果是,那么不需要操作,如果存在一个元素错位,那么需要一次操作(操作后n-1个元素)。
如果1不在a[1]处,看1是否在a[2] ~ a[n - 1] 处,如果在,那么看n 是否在a[n] 处,如果在,那么需要一步操作(操作前n - 1个),如果不在,需要两步 (先把1放到a[1]处,再操作后n -1 个)。
如果1不在上述两种位置,而是再a[n]处,那么看n 的位置,如果n不在a[1] 处,那么需要两步(先把n 放到a[n]处,再操作前n - 1 个),如果n 再a[1] 处,那么需要3步,(先把n挪动位置,然后执行上述过程)。
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while (T--) {
int a[99];
int n; cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
if (a[1] == 1) {//如果1 在a[1]处,看后面元素是否各就各位。
int flag = 0;
for (int i = 2; i <= n; i++) {
if (a[i] != i) {
flag = 1;
break;
}
}
cout << flag << endl;
continue;
}
if (a[n] == 1) {//如果1 在a[n]处,判断n 是否在a[1]处
cout << 2 + (a[1] == n) << endl;
continue;
}
//如果1在中间某处,判断n是否在a[n]处。
cout << 1 + (a[n] != n) << endl;
}
return 0;
}