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
#include <iostream>
#include <map>
#include <utility>

int64_t result = 0;
std::string input;
int64_t cntA = 0, cntB = 0, cntC = 0;
std::map<std::pair<int64_t, int64_t>, int64_t> mapThrees = {{std::make_pair(0, 0), 1}}, mapA = {{std::make_pair(0, 0), 1}}, mapB = {{std::make_pair(0, 0), 1}}, mapC = {{std::make_pair(0, 0), 1}};

int main() {
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(NULL);
    std::cin >> input;

    char lastChar = 'z';
    int64_t seq;
    for (int i = 0; i < input.length(); i++) {
        if (input[i] != lastChar) {
            seq = 0;
        }
        seq++;
        lastChar = input[i];
        result += seq;
        switch (input[i]) {
            case 'a':
                cntA++;
                mapA[std::make_pair(cntB - cntC, cntA)]++;
                result += mapB[std::make_pair(cntC - cntA, cntB)]++;
                result += mapC[std::make_pair(cntA - cntB, cntC)]++;
                break;
            case 'b':
                cntB++;
                mapB[std::make_pair(cntC - cntA, cntB)]++;
                result += mapA[std::make_pair(cntB - cntC, cntA)]++;
                result += mapC[std::make_pair(cntA - cntB, cntC)]++;
                break;
            default: // 'c'
                cntC++;
                mapC[std::make_pair(cntA - cntB, cntC)]++;
                result += mapA[std::make_pair(cntB - cntC, cntA)]++;
                result += mapB[std::make_pair(cntC - cntA, cntB)]++;
                break;
        }
        result += mapThrees[std::make_pair(cntA - cntB, cntB - cntC)]++;
    }

    std::cout << result;
}