CF1905F Field Should Not Be Empty

· · 题解

奶龙题,场切了。

思路:

由于是排列,所以 x 是好的当且仅当 p_x = x 且 p_1, \cdots, p_{x - 1} 构成 1 \sim x - 1 的排列。

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

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

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

完整代码:

#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;
}