CF2237D

· · 题解

赛时光速切了此题,间接助我上 CM。

做法

一个二进制字符串是美丽的当且仅当。

  1. 长度为 1;(总是美丽)
  2. 或者长度 \ge 2,同时满足。

考虑正难则反。

等价地,所有不美丽的子串可以分为两类。

总方案减去它们两个不合法的即可。

代码

::::success[Accepted code]

#include<bits/stdc++.h>
using namespace std;
#define int long long
int n;
string s;
void solve()
{
    cin>>n>>s;
    int tot=n*(n+1)/2;
    int cnt0=1,cnt1=0,cnt2=0;
    int pre=0;
    for(auto c:s)
    {
        if(c=='0') pre=(pre+1)%3;
        else pre=(pre+2)%3;
        if(pre==0) cnt0++;
        else if(pre==1) cnt1++;
        else cnt2++;
    }
    int res=cnt0*(cnt0-1)/2+cnt1*(cnt1-1)/2+cnt2*(cnt2-1)/2;
    int odd=0;
    int i=0;
    while(i<n)
    {
        int j=i;
        while(j+1<n&&s[j]!=s[j+1])
        {
            j++;
        }
        int len=j-i+1;
        int m=(len-1)/2;
        odd=odd+m*(len-m-1);
        i=j+1;
    }
    int ans=tot-res-odd;
    cout<<ans<<"\n";
}

signed main()
{
    ios::sync_with_stdio(0);
    cout.tie(0);
    cin.tie(0);
    int T;cin>>T;
    while(T--)solve();
    return 0;
}

::::