题解:CF1905F Field Should Not Be Empty
WorldMachine · · 题解
线性,虽然有个哈希表就是了。
首先特判掉
考虑什么时候交换
交换
总贡献是
#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();
}