#define make_pair mp #define emplace_back pb #include <bits/stdc++.h> using namespace std; mt19937 mt_rand(time(0)); const int N = 3e5 + 5; int n, a, b, c; char s[N]; map<int, map<int, int>> m; map<int, int> m2; long long res; int main() { scanf("%s", &s); m[0][0] = 1; while(s[n]) { if(s[n] == 'a') { a++; } else if(s[n] == 'b') { b++; } else { c++; } res += m[a-b][a-c]; m[a-b][a-c]++; n++; } int first = 0; for(int i=1;i<=n;i++) { if(s[i] != s[i-1]) { long long num = i - first; num *= (num + 1); num /= 2; res += num; first = i; } } char cc = 'a' - 1; char ccc = 'a'; for(int j=0;j<3;j++) { cc++; ccc++; if(ccc > 'c') ccc = 'a'; m2.clear(); m2[0] = 1; int sub = 0; for(int i=0;i<n;i++) { if(s[i] == cc) { m2.clear(); m2[0] = 0; sub = 0; } if(s[i] == ccc) sub++; else sub--; res += m2[sub]; m2[sub]++; } } printf("%lld\n", res); 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 | #define make_pair mp #define emplace_back pb #include <bits/stdc++.h> using namespace std; mt19937 mt_rand(time(0)); const int N = 3e5 + 5; int n, a, b, c; char s[N]; map<int, map<int, int>> m; map<int, int> m2; long long res; int main() { scanf("%s", &s); m[0][0] = 1; while(s[n]) { if(s[n] == 'a') { a++; } else if(s[n] == 'b') { b++; } else { c++; } res += m[a-b][a-c]; m[a-b][a-c]++; n++; } int first = 0; for(int i=1;i<=n;i++) { if(s[i] != s[i-1]) { long long num = i - first; num *= (num + 1); num /= 2; res += num; first = i; } } char cc = 'a' - 1; char ccc = 'a'; for(int j=0;j<3;j++) { cc++; ccc++; if(ccc > 'c') ccc = 'a'; m2.clear(); m2[0] = 1; int sub = 0; for(int i=0;i<n;i++) { if(s[i] == cc) { m2.clear(); m2[0] = 0; sub = 0; } if(s[i] == ccc) sub++; else sub--; res += m2[sub]; m2[sub]++; } } printf("%lld\n", res); return 0; } |