题目链接
链接:登录—专业IT笔试面试备考平台_牛客网
来源:牛客网
题目描述
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.
示例1
输入
4 4 4 2 1 3 6 4 2 5 1 3 6 8 5 4 6 3 1 8 2 7 10 1 2 9 10 3 6 8 4 5 7
输出
1 1 3 2
题目大意
给定一个排列,每次选择四个位置任意交换其中的元素,求排序的最小次数。
解题思路
考虑 i→pi构成的图中的环,对于长度为 len 的环
len==3,4可以一次排序好
两个 len == 2的环可以一次排好
对于 len>4的环,每次操作可以排好其中三个元素,环长变为 len - 3因此记录有多少个环最终长度为2,将其两两合并处理即可。
#include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
const int N = 1e6 + 5;
int f[N], g[N];
void solve() {
int n;
cin >> n;
int ans = 0;
for (int i = 1; i <= n; i++) cin >> f[i];
g[2] = g[3] = g[4] = 0;
//考虑 i→gi构成的图中的环,对于长度为 len 的环
for (int i = 1; i <= n; i++) {
if (!f[i]) continue;
int s = 1;
int u = f[i];
f[i] = 0;
while (1) {
if (u == i) break;
int x = f[u];
f[u] = 0, u = x, s++;
}
/*
对于 len > 4的环,
每次操作可以排好其中三个元素,
环长变为 len - 3因此记录有多少个环最终长度为2,
将其两两合并处理即可。
*/
while (s > 4) s -= 3, ans++;
g[s]++;
}
ans += g[3] + g[4] + (g[2] + 1) / 2;
cout << ans << endl;
return;
}
signed main() {
std::ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
欢迎讨论!!!