CF1905F Field Should Not Be Empty
Genius_Star · · 题解
奶龙题,场切了。
思路:
由于是排列,所以
于是考虑分析
-
若
p_i = i :-
若
p_1, \cdots, p_{i - 1} 已经构成1 \sim i - 1 的排列:那么只要交换的x, y 不跨过i 即可,即都<i 或者都>i 。 -
否则因为只能交换一次,那么前面
1 \sim i - 1 只能恰好缺一个,否则i 不可能是好的,找到缺的那个位置,那么存在一个唯一的交换操作(a, b) 使得i 是好的。
-
-
否则
p_i \ne i :-
若
p_1, \cdots, p_{i - 1} 已经构成1 \sim i - 1 的排列:那么找到p_x = i ,交换x, i 即可。 -
否则若
p_1, \cdots, p_{i - 1}, p_i 已经构成1 \sim i 的排列:那交换前面的值i 所在位置与i 即可。
-
此时,上面有
于是离线下来扫一遍即可,时间复杂度为
完整代码:
#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;
}