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

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

    std::string text;
    std::cin >> text;
    
    int a = 0;
    int left = 0, right = text.size() - 1, result = 0;

    for (char c : text) if (c == 'a') a++;
    
    if (text.size() % 2 == 0 && a % 2 == 1) {
        std::cout << -1; return 0;
    }
 
    while (left < right)
    {
        int l = left, r = right;

        while (text[l] != text[r]) r--;

        if (l == r) {
            std::swap(text[r], text[r + 1]);
            result++;
            continue;
        }

        while (r < right) {
            std::swap(text[r], text[r + 1]);
            result++;
            r++;
        }
        
        left++, right--;
    }

    std::cout << result;
    return 0;
}