赛时光速切了此题,间接助我上 CM。
做法
一个二进制字符串是美丽的当且仅当。
- 长度为 ;(总是美丽)
- 或者长度 ,同时满足。
- 字符串的模 和不为 ;(字符
0权值为,字符1权值为,取模) - 字符串不是交替串。(即不是
0101...或1010...这种没有相邻相同字符的串)
考虑正难则反。
等价地,所有不美丽的子串可以分为两类。
- 模 和为 的子串;(其中包含所有偶数长度的交替串)
- 长度 且为奇数长度的交替串。(无法进行任何操作)
总方案减去它们两个不合法的即可。
代码
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;
}