前言
constructive algorithms——一生之敌
首先如果是有序的,那么操作次数为0
如果元素是错位的,那么肯定一次就能归位,关键是如果是有的错位有的没错位,比如"1 5 3 4 2"。这种,第一次必须要打乱位置,这个肯定可以操作,比如变成"3 1 4 5 2",然后一次就成功了
需要注意的是不要漏掉有一段连续错位的情况,也是操作一次即可
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <math.h>
#include <cstdio>
#include <string>
#include <bitset>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define ins insert
#define lowbit(x) (x&(-x))
#define mkp(x,y) make_pair(x,y)
#define mem(a,x) memset(a,x,sizeof a);
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int,int> P;
const double eps=1e-8;
const double pi=acos(-1.0);
const int inf=0x3f3f3f3f;
const ll INF=1e18;
const int Mod=1e9+7;
const int maxn=2e5+10;
int n;
int a[maxn];
bool check1(){
for(int i=1;i<=n;i++)
if(a[i]!=i)
return false;
return true;
}
bool check2(){
int cnt=0;
for(int i=1;i<=n;i++)
if(a[i]!=i){
cnt++;
int j=i;
while(a[j]!=j && j<=n) j++;
i=j-1;
}
if(cnt==1) return true;
return false;
}
int main(){
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int t;
cin>>t;
while(t--){
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
if(check1()){
puts("0");
}else if(check2())
puts("1");
else puts("2");
}
return 0;
}