我们发现不好统计,考虑容斥。
答案为总共的减去 的减去 的减去 的加上两倍 的。
我们发现是好做的,直接考虑前缀和 ,直接将前缀和的差代入放进 map 里面就行。
#include<bits/stdc++.h>
#define int long long
using namespace std;
namespace Momoyu{
void prepare(){
}
const int maxn=3e5+10;
int n,q;
map<int,int>mp;
int sa[maxn],sb[maxn],sc[maxn];
void main(){
cin>>n;
map<int,int>mp1,mp2,mp3;
map<pair<int,int>,int>mp4;
int ans=0;
mp1[0]=mp2[0]=mp3[0]=mp4[{0,0}]=1;
for(int i=1;i<=n;i++){
char ch;
cin>>ch;
sa[i]=sa[i-1],sb[i]=sb[i-1],sc[i]=sc[i-1];
if(ch=='A')sa[i]++;
if(ch=='B')sb[i]++;
if(ch=='C')sc[i]++;
int x=sa[i]-sb[i],y=sb[i]-sc[i];
int z=x+y;
ans+=mp1[x]+mp2[y]+mp3[z];
mp1[x]++,mp2[y]++,mp3[z]++;
ans-=2*mp4[{x,y}];
mp4[{x,y}]++;
}
cout<<n*(n+1)/2-ans;
}
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(NULL),cout.tie(NULL);
Momoyu::prepare();
Momoyu::main();
}