题解:CF137E Last Chance

· · 题解

这道题和 ABC 441 E 相似,定义满足 s\times cnt(1)\le t\times cnt(0) 的 01 串为“好串”,其中 cnt(c) 表示字符 c 出现的个数。这两题都是有关 01 串中“好串”子串的问题。

对于这一类题,我们考虑前缀和维护区间 01 个数,那么对于子串 [l,r],令 sum1(i) 和 sum0(i) 分别表示前缀 01 个数,则条件变为:

s\times sum1(r)-s\times sum1(l-1)\le t\times sum0(r)-t\times sum0(l-1)

移项得

t\times sum0(l-1)-s\times sum1(l-1)\le t\times sum0(r)-s\times sum1(r)

令 f(i)=t\times sum0(i)-s\times sum1(i),则有 f(l-1)\le f(r)。

我们可以考虑固定左端点,统计右端点。对于 ABC 441 E 等要求统计个数的题,我们考虑用权值树状数组;对于本题,我们考虑维护 f(i) 的后缀最大值,并二分得到最大的 j 使得 f(j)\ge f(i) (i\le j)。

综上,对于这一类的题目,本质为和 f(i) 有关的一个序列问题,事实上也可以考察这样一个问题: :::info[question] 给定一个 01 串 s,定义一个子串 [l,r] 是“好串”,当且仅当 \forall l\le i\le j\le r,[i,j] 中 1 的个数均小于 0 的个数,求“好串”的个数。 ::: :::success[solution] 本质上就是求 f(i) 的单调递增的子序列个数,双指针即可。 ::: :::success[本题代码]

const int N=2e5+99;
int n;
string s;
int sum1[N],sum2[N];
bool check(char ch){
    if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U'||
        ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'){
        return 1;
    }else{
        return 0;
    }
}
int f[N],g[N];
signed main(){
    cin>>s;
    n=s.size();
    s=' '+s;
    for(int i=1;i<=n;i++){
        sum1[i]=sum1[i-1]+check(s[i]);
        sum2[i]=sum2[i-1]+(!check(s[i]));
    }
    f[0]=-1e18;
    for(int i=n;i;i--){
        f[n-i+1]=max(f[n-i],2*sum2[i]-sum1[i]);
        g[i]=n-(lower_bound(f+1,f+1+(n-i+1),2*sum2[i-1]-sum1[i-1])-f)-i+2;
    }
    int maxx=-1;
    for(int i=1;i<=n;i++){
        maxx=max(maxx,g[i]);
    }
    if(maxx==0){
        cout<<"No solution\n";
        return 0;
    }
    cout<<maxx<<' ';
    int cnt=0;
    for(int i=1;i<=n;i++){
        if(g[i]==maxx){
            cnt++;
        }
    }
    cout<<cnt<<endl;
    return 0;
}

:::