题解:P11561 【MX-X7-T2】[LSOT-3] 姬誉蛙

· · 题解

P11561 题解

容易发现,答案具有单调性。

然后,如果确定了最大权值,那么可以用贪心,线性求解最少要分成几段。
具体的,如果现在加上这个数字后超过了权值,肯定要新开一段,否则,肯定尽可能放在当前段。

由于最大权值是 O(n^2) 的,二分复杂度为 O(n\log{n})。

代码:

#include<bits/stdc++.h>

using namespace std;

char x[1000001];

int check(int n,long long maxn)//确定最大权值,返回最少几段
{
    long long ma=0,mb=0;
    int ans=0;
    for(int i=0;i<n;i++)
    {
        if(x[i]&1)ma++;//这里用了 0 和 1 的 ascll 码特性
//如果为 '0',就会让 mb 加一,否则 ma 加一。
        else mb++;
        if(ma*mb>maxn)
        {
            ans++,ma=0,mb=0;
            if(x[i]&1)ma++;
            else mb++;
        }
    }
    ans++;//最后一段
    return ans;
}

int main()
{
    ios::sync_with_stdio(false);cin.tie(0);
    int n,t;cin>>n>>t;
    cin>>x;
    long long l=-1,r=1e15;//r 大于 n^2,够用了
    while(l<r-1)
    {
        long long mid=(l+r)>>1;
        if(check(n,mid)>t)l=mid;
        else r=mid;
    }
    cout<<r;
    return 0;
}