#include <bits/stdc++.h>
using namespace std;
int n,k;
long long y,ans;
string s;
int pc[300005],pa[300005],pb[300005],pab[300005],pbc[300005],pca[300005];
map<pair<int,int>,int >m;
map<pair<int,int>,int >ma;
map<pair<int,int>,int >mb;
map<pair<int,int>,int >mc;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cin>>s;
n = s.size();
k = 1;ans = 0;
for(int i=1;i<=n;i++)
{
pc[i] = pc[i - 1];
pb[i] = pb[i - 1];
pa[i] = pa[i - 1];
if(s[i - 1] == 'c')
pc[i]++;
else if(s[i - 1] == 'b')
pb[i]++;
else
pa[i]++;
pab[i] = pb[i] - pa[i];
pbc[i] = pc[i] - pb[i];
pca[i] = pa[i] - pc[i];
if(i == n || s[i - 1] != s[i])
{
y = k;
y = y * (y + 1) / 2;
ans += y;
k = 1;
}
else
k++;
}
for(int i=0;i<=n;i++)
{
ans += ma[{pbc[i],pa[i]}];
ans += mb[{pca[i],pb[i]}];
ans += mc[{pab[i],pc[i]}];
ans += m[{pab[i],3 * pc[i] - i}];
ma[{pbc[i],pa[i]}] ++;
mb[{pca[i],pb[i]}] ++;
mc[{pab[i],pc[i]}] ++;
m[{pab[i],3 * pc[i] - i}] ++;
}
cout<<ans;
return 0;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | #include <bits/stdc++.h> using namespace std; int n,k; long long y,ans; string s; int pc[300005],pa[300005],pb[300005],pab[300005],pbc[300005],pca[300005]; map<pair<int,int>,int >m; map<pair<int,int>,int >ma; map<pair<int,int>,int >mb; map<pair<int,int>,int >mc; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>s; n = s.size(); k = 1;ans = 0; for(int i=1;i<=n;i++) { pc[i] = pc[i - 1]; pb[i] = pb[i - 1]; pa[i] = pa[i - 1]; if(s[i - 1] == 'c') pc[i]++; else if(s[i - 1] == 'b') pb[i]++; else pa[i]++; pab[i] = pb[i] - pa[i]; pbc[i] = pc[i] - pb[i]; pca[i] = pa[i] - pc[i]; if(i == n || s[i - 1] != s[i]) { y = k; y = y * (y + 1) / 2; ans += y; k = 1; } else k++; } for(int i=0;i<=n;i++) { ans += ma[{pbc[i],pa[i]}]; ans += mb[{pca[i],pb[i]}]; ans += mc[{pab[i],pc[i]}]; ans += m[{pab[i],3 * pc[i] - i}]; ma[{pbc[i],pa[i]}] ++; mb[{pca[i],pb[i]}] ++; mc[{pab[i],pc[i]}] ++; m[{pab[i],3 * pc[i] - i}] ++; } cout<<ans; return 0; } |
English