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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <map>

using namespace std;

map<pair<int, int>, int> abc_prefixes;
map<int, int> ab_prefixes;
map<int, int> ac_prefixes;
map<int, int> bc_prefixes;

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);

  string input;
  cin >> input;

  abc_prefixes[make_pair(0, 0)] = 1;
  ab_prefixes[0] = 1;
  ac_prefixes[0] = 1;
  bc_prefixes[0] = 1;

  long long result = 0;
  int a_counter = 0;
  int b_counter = 0;
  int c_counter = 0;
  int same_letter_counter = 0;
  char prev_letter = 0;

  for (char letter : input) {

    if (letter == prev_letter) {
      same_letter_counter++;
    }
    else {
      same_letter_counter = 1;
      prev_letter = letter;
    }

    result += same_letter_counter;

    if (letter == 'a') {
      a_counter++;

      bc_prefixes.clear();
    }
    else if (letter == 'b') {
      b_counter++;

      ac_prefixes.clear();
    }
    else {
      c_counter++;

      ab_prefixes.clear();
    }

    int ab_diff = a_counter - b_counter;
    int bc_diff = b_counter - c_counter;
    int ac_diff = a_counter - c_counter;

    result += abc_prefixes[make_pair(ab_diff, bc_diff)];
    result += ab_prefixes[ab_diff];
    result += ac_prefixes[ac_diff];
    result += bc_prefixes[bc_diff];

    abc_prefixes[make_pair(ab_diff, bc_diff)] += 1;
    ab_prefixes[ab_diff] += 1;
    ac_prefixes[ac_diff] += 1;
    bc_prefixes[bc_diff] += 1;
  }

  cout << result << '\n';

  return 0;
}