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
3
4
1 3 2 4
3
1 2 3
5
2 1 4 5 3
Output
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].
题意:给你一个数组,可以改变这个数组里面某一个区间里数的排列次序,但是不能是整个数组区间。问:通过多少最少的排列次数,能将该数组按照递增的顺序排列。
==题解:==一共只有4中情况,第一种
是该数组原本就是递增的,所以为0;
第二种
,最小值在第一位,只需要把剩下的数从小到大排列就行,所以为1;
第三种
,最大值在第一位,并且最小值在最后一位,因为不能对整个数组进行操作,所以所以先把2到n从小到大排列、此时最小值排在第二位,再把第一位和第二位进行交换、此时最小值在第一位,根据第二种情况,只需要把剩下的数从小到大排列就行,所以为3;
第四种
,最小值在中间,先操作一次,把最小值放到第一位,此时符合第二种情况,所以为2;
AC代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;
typedef long long ll;
int a[60],b[60];
const int inf=0x3f3f3f3f;
//a是排序之前的,b是排序之后的
int main()
{
int t;
scanf("%d",&t);
int minn,maxx;
while(t--)
{
int n,i,j,k;
scanf("%d",&n);
for(i=1; i<=n; i++)
{
scanf("%d",&b[i]);
a[i]=b[i];
}
sort(b+1,b+1+n);
minn=1,maxx=n;
for(i=1; i<=n; i++)
if(a[i]!=b[i])
break;
if(i==n+1)//说明a数组和b数组相等
{
printf("0\n");
continue;
}
if(minn==a[1]||maxx==a[n])
printf("1\n");
else if(minn==a[n]&&maxx==a[1])
printf("3\n");
else
printf("2\n");
}
return 0;
}