跳到正文

题解

CF2237D

Gaochenxi103_QAQ约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年6月20日
收录
2026年6月23日
更新
2026年11月21日
篇幅
约 2 分钟
题目
CF2237D

版本

  1. v1当前

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

做法

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

  1. 长度为 11;(总是美丽)
  2. 或者长度 ≥2\ge 2,同时满足。
  • 字符串的模 33 和不为 00;(字符0权值为11,字符1权值为22,取模33)
  • 字符串不是交替串。(即不是0101...或1010...这种没有相邻相同字符的串)

考虑正难则反。

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

  • 模 33 和为 00 的子串;(其中包含所有偶数长度的交替串)
  • 长度 ≥3\ge3 且为奇数长度的交替串。(无法进行任何操作)

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

代码

Accepted code
C++
#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;
}
原文