Given a permutation†\textstyle ^\dagger† of length n\textstyle nn. In one operation, you can choose at most four elements from the permutation and swap their positions arbitrarily. What is the minimum number of operations required to sort the permutation in ascending order?
†\textstyle ^\dagger† A permutation of length n\textstyle nn is an array consisting of n\textstyle nn distinct integers from 1\textstyle 11 to n\textstyle nn in arbitrary order. For example, [2,3,1,5,4]\textstyle [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2]\textstyle [1,2,2][1,2,2] is not a permutation (2\textstyle 22 appears twice in the array), and [1,3,4]\textstyle [1,3,4][1,3,4] is also not a permutation (n=3\textstyle n=3n=3 but there is 4\textstyle 44 in the array).
输入描述:
Each test contains multiple test cases. The first line contains the number of test cases t\textstyle tt (1≤t≤105\textstyle 1 \leq t \leq 10^51≤t≤105). The description of the test cases follows.
The first line of each test case contains an integer n\textstyle nn (1≤n≤106\textstyle 1 \leq n \leq 10^61≤n≤106), indicating the length of the permutation.
The second line contains a permutation a1,a2,…,an\textstyle a_1, a_2, \ldots, a_na1,a2,…,an.
It is guaranteed that the sum of n\textstyle nn across all test cases does not exceed 106\textstyle 10^6106.
输出描述:
For each test case, output a single integer, indicating the minimum number of operations required to sort the permutation.
很妙的点就是for(auto ) 里面的判断 通过循环的环的大小直接判断次数,但是考虑过就知道像7等等的数字的循环是先3再4的所以,相似的情况是需要判断,就有X%3==1的ans--,最后还要对答案向上取整
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
const int N = 1e6+5;
int s[N];
int u[N];
int v[N];
int find(int x){
return s[x]==x?s[x]:s[x]=find(s[x]);
}
void merge(int x,int y){
int tx=find(x);
int ty=find(y);
if(tx!=ty) s[tx]=ty;
return;
}
int n;
void init(){
for(int i=0;i<=n;i++)v[i]=0;
for(int i=1;i<=n;i++)s[i]=i;
}
void solve(){
cin>>n;
init();
int sum=0;
for(int i=1;i<=n;i++){
cin>>u[i];
merge(i,u[i]);
}
unordered_map<int,int> p;
for(int i=1;i<=n;i++){
p[find(i)] ++;
}
int ans=0;
for(auto i:p){
ans += i.second / 3 + i.second;
if(i.second % 3 == 1) ans --;
}
cout<<(ans+3)/4<<endl;
}
signed main() {
IOS
int T;
cin>>T;
while(T--) {
solve();
}
return 0;
}