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
#include <iostream>
#include <string>

bool isBalanced(int a, int b, int c);

int main()
{
    std::string s;
    std::cin >> s;
    long long counter = 0; // how many balanced words
    for (int i = 0; i < s.size(); i++)
    {
        int aCounter = 0, bCounter = 0, cCounter = 0;
        for (int j = i; j < s.size(); j++)
        {
            if (s[j] == 'a')
                aCounter++;
            else if (s[j] == 'b')
                bCounter++;
            else
                cCounter++;
            
            if (isBalanced(aCounter, bCounter, cCounter))
                counter++;
        }
    }

    std::cout << counter;
}

bool isBalanced(int a, int b, int c)
{
    if (a > 0)
    {
        if ((a == b || b == 0) && (a == c || c == 0))
            return true;
        return false;
    }
    if (b > 0)
    {
        if ((b == a || a == 0) && (b == c || c == 0))
            return true;
        return false;
    }
    if (c > 0)
    {
        if ((c == a || a == 0) && (c == b || b == 0))
            return true;
        return false;
    }
}