跳到正文

题解

CF1905F Field Should Not Be Empty

Genius_Star约 5 分钟
原文

这是 2025年11月4日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年11月3日
收录
2025年12月12日
更新
2026年9月28日
篇幅
约 5 分钟
题目
CF1905F

版本

  1. v2当前
  2. v1

奶龙题,场切了。

思路:

由于是排列,所以 xx 是好的当且仅当 px=xp_x = x 且 p1,⋯ ,px−1p_1, \cdots, p_{x - 1} 构成 1∼x−11 \sim x - 1 的排列。

于是考虑分析 xx 是好的会给哪些交换产生影响:

  • 若 pi=ip_i = i:

    • 若 p1,⋯ ,pi−1p_1, \cdots, p_{i - 1} 已经构成 1∼i−11 \sim i - 1 的排列:那么只要交换的 x,yx, y 不跨过 ii 即可,即都 <i<i 或者都 >i>i。

    • 否则因为只能交换一次,那么前面 1∼i−11 \sim i - 1 只能恰好缺一个,否则 ii 不可能是好的,找到缺的那个位置,那么存在一个唯一的交换操作 (a,b)(a, b) 使得 ii 是好的。

  • 否则 pi≠ip_i \ne i:

    • 若 p1,⋯ ,pi−1p_1, \cdots, p_{i - 1} 已经构成 1∼i−11 \sim i - 1 的排列:那么找到 px=ip_x = i,交换 x,ix, i 即可。

    • 否则若 p1,⋯ ,pi−1,pip_1, \cdots, p_{i - 1}, p_i 已经构成 1∼i1 \sim i 的排列:那交换前面的值 ii 所在位置与 ii 即可。

此时,上面有 O(n)O(n) 级别个的特殊的交换会额外增加贡献,其它交换都是根据是否满足第一个那个跨过的条件来加贡献的。

于是离线下来扫一遍即可,时间复杂度为 O(Nlog⁡N)O(N \log N)。

完整代码:

C++
#include<bits/stdc++.h>
#define ls(k) k << 1
#define rs(k) k << 1 | 1
#define lowbit(x) x & (-x)
#define fi first
#define se second
#define popcnt(x) __builtin_popcount(x)
#define open(s1, s2) freopen(s1, "r", stdin), freopen(s2, "w", stdout);
using namespace std;
typedef __int128 __;
typedef long double lb;
typedef double db;
typedef unsigned long long ull;
typedef long long ll;
bool Begin;
const int N = 3e5 + 10;
inline ll read(){
	ll x = 0, f = 1;
	char c = getchar();
	while(c < '0' || c > '9'){
		if(c == '-') f = -1;
		c = getchar();
	}
	while(c >= '0' && c <= '9'){
		x = (x << 1) + (x << 3) + (c ^ 48);
		c = getchar();
	}
	return x * f;
}
inline void write(ll x){
	if(x < 0){ putchar('-'); x = -x; }
	if(x > 9) write(x / 10);
	putchar(x % 10 + '0');
}
int T, n;
int a[N], id[N], s[N], h[N];
set<int> S;
unordered_map<int, int> mp[N];
inline void solve(){
	S.clear();
	n = read();
	for(int i = 1; i <= n; ++i){
		a[i] = read();
		id[a[i]] = i;
		S.insert(i);
		s[i] = 0;
		mp[i].clear();
	}
	S.insert(n + 1);
	int mx = 0;
	for(int i = 1; i <= n; ++i){
		if(a[i] == i){
			auto it = S.begin();
			if((*it) == i)
			  ++s[i];
			else{
				int x = (*it);
				++it;
				if((*it) == i){
					// id[mx], x
//					cerr << id[mx] << ' ' << x << '\n';
					++mp[id[mx]][id[x]];
				}
			}
		}
		else{
			auto it = S.begin();
			if((*it) == i){
//				cerr << i << ' ' << id[i] << '\n';
			    ++mp[i][id[i]];
			}
			else if((*it) == a[i]){
				++it;
				if((*it) == i + 1){
//					cerr << id[i] << ' ' << i << '\n';
					++mp[id[i]][i];
				}
			}
		}
		mx = max(mx, a[i]);
		S.erase(a[i]);
//		cerr << s[i] << '\n';
		h[i] = h[i - 1] + s[i];
	}
	int mn = 1e9, ans = 0;
	for(int i = n; i >= 1; --i){
		ans = max(ans, h[i - 1] + h[n] - mn);
		for(auto t : mp[i]){
			int j = t.fi, num = t.se;
			ans = max(ans, h[i - 1] + h[n] - h[j] + num);
		}
		mn = min(mn, h[i]);
		// [x, y]
		// h[x - 1] + h[n] - h[y]
	}
	write(ans);
	putchar('\n');
}
bool End;
int main(){
//	open("strike.in", "strike.out");
	T = read();
	while(T--)
		solve();
	return 0;
}