题解 CF2238E Cake Trial

· · 题解

题解 CF2238E Cake Trial

另外回应一下@wurang 大佬的质疑:

并不存在 n^2 的反悔贪心做法,这个不知道怎么来的算法既没有实现也没有证明,浪费了我一晚上

您的质疑确实不无道理。不过巧了,我也在跟 dmy 并刚好实现了一下,既然您要就补上。您也可以去 CF 的 Status 页面搜 Starsilk 大神的实现。

其他题

蛋糕是个谎言。

——《传送门》

给定一个长为 n、字符集为 TFN 的字符串。Alice 将所有 N 换为 T 或 F,然后 Bob 选择一个区间,使得区间内的 T 的个数(可能为空)和区间外的 F 的个数之和最小。求这个最小的和最大可以是多少。

数据范围:多测,\sum n^3\le 500^3。

:::info[提示一] 用 -1 表示 T,1 表示 F,则 Bob 的选择一段区间代价是什么? :::

:::success[做法一]{open} 先看提示。

Bob 选择一段区间的代价是总 F 个数减去选择的区间和,因为区间和是区间内 F 的个数减去 T 的个数,括号打开就是区间外 F 的个数加区间内 T 的个数。

所以 Bob 一定是找最大子段(可以为空)和,而当总 F 个数和最大子段和相同时,在本题的意义下就是本质相同的填法,所以要另外维护总 F 个数。

于是设 dp_{i,j,k} 表示填了前 i 个,填了 j 个 F,以当前位置结尾的最大子段和为 k 时的最大子段和,分类转移即为 O(n^3)。

:::success[做法二]{open}

Solution from @Starsilk.

我们用 n 减一下答案,即考虑最小化总 T 个数加最大子段和。枚举最大子段和,则需要最小化总 T 个数。考虑反悔贪心,即当前能 F 则 F,如果最大子段和爆了则把最后一个可以换成 T 的 F 换掉。这个过程是 O(n) 的,所以单组复杂度是 O(n^2) 的。

注意由于把前面的 F 换成 T 会导致当前的子段和减小,进而可能引发以当前位置结尾的最大子段变化,所以记录的可以通过将 F 换成 T 来减小的子段和的上限(代码中 cnt)应时刻不超过当前位置结尾的最大子段和。

//Please ignore those headfiles.I write them just because
//DEV-C++ won't support completion if i use <bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<cmath>
#include<cctype>
#include<random>
#include<string>
#include<algorithm>
#include<vector>
#include<map>
#include<unordered_map>
#include<set>
#include<queue>
#define ll long long
#define ull unsigned long long
#define lf double
#define ld long double
#define LL __int128
#define ui unsigned int
using namespace std;
ll T,n;
string s;
int main(){
    ios::sync_with_stdio(0);
    cin>>T;
    while(T--){
        cin>>n>>s;
        ll ans=n;
        for(int i=0;i<=n;i++){
            ll now=0,cnt=0,cntt=0;
            for(int j=0;j<n;j++){
                if(s[j]=='T'){
                    now--;
                    cntt++;
                    now=max(now,0ll);
                }
                else{
                    now++;
                    cnt+=(s[j]=='N')*2;
                }
                cnt=min(now,cnt);
                if(now>i){
                    if(cnt){
                        cntt++;
                        now-=min(cnt,2ll);
                        cnt-=min(cnt,2ll);
                    }
                    else{
                        cntt=n;
                        break;
                    }
                }
            }
            ans=min(ans,i+cntt);
        }
        cout<<n-ans<<endl;
    }
    return 0;
}

:::