线性,虽然有个哈希表就是了。
首先特判掉 的情况,这时交换一次后至少会有 个位置变得不合法,答案为 。
考虑什么时候交换 更优,首先一定有 ,否则中间所有合法的 都会变得不合法。
交换 后会有一些新的 由不合法变得合法,这样的 要么前后各有一个数不符合条件,且这对数就是 ;要么交换的是 且交换之后变得合法。
总贡献是 的,因此有贡献的交换对数也是 的,用哈希表记下来最后找最大值即可,时间复杂度为 。
#include <bits/stdc++.h>
using namespace std;
#define rep(i, l, r) for (int i = l; i <= r; i++)
const int N = 2e5 + 5;
int T, n, a[N], p[N], mx[N], mxp[N], c[N];
struct Hash { size_t operator()(const pair<int, int> &p) const { return hash<int>()(p.first) ^ hash<int>()(p.second); }; };
unordered_map<pair<int, int>, int, Hash> mp;
void solve() {
cin >> n, mp.clear(); int cnt = 0, cur = 0, flg = 1, ans = 0;
rep(i, 1, n) cin >> a[i], p[a[i]] = i, mx[i] = max(mx[i - 1], a[i]), flg &= a[i] == i;
if (flg) return cout << n - 2 << '\n', void();
rep(i, 1, n) mxp[i] = max(mxp[i - 1], p[i]), c[i] = 0;
rep(i, 1, n) {
if (a[i] <= i) cur++; cur += c[i], c[a[i]]++;
if (a[i] == i) { if (mx[i] == i) cnt++; else if (cur == i - 1) mp[{p[mx[i]], mxp[i]}]++; }
else if (a[i] > i) { if (mx[a[i]] == a[i]) mp[{i, a[i]}]++; }
else { if (mxp[a[i] - 1] == a[i] - 1) mp[{a[i], i}]++; }
}
for (auto [x, y] : mp) ans = max(ans, y); cout << cnt + ans << '\n';
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> T; while (T--) solve();
}