给定整数 n 和一个 1∼n 的排列 p.
你可以对排列 p 进行下列操作任意次:
选择整数 i, j(1 ≤ i < j ≤ n),然后交换 pi, pj 的值.
你需要求出至少需要进行上述操作多少次才能使 p 恰有一个逆序对.
每个测试点包含 t 组数据.
1≤t≤1e4, 2≤n, ∑n≤2e5.
建边 i -> i 在 p 中出现的位置(下标), 这张图一定是若干个环.
操作等价于交换两个节点的后继节点,每次操作至多只会使环数 + 1,
1~n 顺序排列对应图的环数为 n, 则对 p 进行排序至少需要
K
=
n
−
环数
K = n - 环数
K=n−环数 次操作.
考虑原问题,若建图后存在两相邻编号节点在同一环内, 则答案为 K + 1.
否则答案为 K - 1.
代码如下:
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0, f = 0; char ch = getchar();
while (!isdigit(ch)) f = ch == '-', ch = getchar();
while (isdigit(ch)) x = (x << 3) + (x << 1) + (ch ^ 48), ch = getchar();
return f ? -x : x;
}
const int N = 2e5 + 10;
int n, a[N], nex[N], st[N];
void work() {
n = read();
for (int i = 1; i <= n; ++i) a[i] = read(), nex[a[i]] = i, st[i] = 0;
int cnt = 0, flag = 1;
for (int i = 1; i <= n; ++i) {
if (!st[i]) {
++cnt; int now = i; st[now] = cnt;
while (!st[nex[now]]) now = nex[now], st[now] = cnt;
}
}
for (int i = 1; i < n; ++i) if (st[i] == st[i + 1]) flag = -1;
printf("%d\n", n - cnt + flag);
}
int main() {
int t = read();
while (t--) work();
return 0;
}