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
#include <string>
#include <iostream>
using namespace std;

string word1;
long sec = 0;

int main() {
    cin >> word1;
    long wSize = word1.size();
    long counta = 0;
    for (char& c : word1) if (c == 'a') counta++;
    long countb = wSize-counta;
    if ((wSize % 2 == 0) && (counta % 2 == 1)) sec = -1;
    else if ((wSize == counta) || (counta == 0)) sec = 0;
    else {
        char letter = counta>countb ? 'b' : 'a';
        long arSize = counta>countb ? countb : counta, *pos, count=0;
        pos = new long[arSize];
        for (long i=0; i<wSize; i++) if (word1[i] == letter) pos[count++] = i;
        for (long j=0; j<(count/2); j++){
            sec += abs(wSize-1-pos[j]-pos[count-1-j]);
        }
        if ((wSize % 2 == 1) && (count % 2 == 1)) sec += abs(wSize/2-pos[count/2]);
    }
    cout << sec;
    return 0;
}