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

using namespace std;

int minMoves(string str) {
    const int n = str.size();
    vector<int> indices;
    int aCount = 0;
    for(int i = 0; i < n; ++i) {
        if(str[i] == 'a') {
            indices.push_back(i);
            aCount++;
        }
    }
    if (indices.size() % 2 == 1 && n % 2 == 0) {
        return -1; 
    }
    int totalMoves = 0;
    vector<int>::iterator it = indices.begin();
    vector<int>::reverse_iterator itBack = indices.rbegin();
    for(int i = 0; i < indices.size()/2; ++i) {
        totalMoves += abs(*it - (*itBack < aCount/2 ? *itBack : n - 1 - *itBack));
        it++;
        itBack++;
    }
    return totalMoves;    
}

int main() {
    string str;
    cin >> str;
    cout << minMoves(str);
    return 0;
}