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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <string>
#include <queue>

using namespace std;

int main() 
{
    string word;
    long count = 0;
    priority_queue<int, vector<int>, greater<int>> aIndexes, bIndexes;

    getline(cin, word);

    int n = word.length();
    int a_count = 0;
    int b_count = 0;
    
    for (int i=0; i<n; i++) {
        if (word[i] == 'a') {
            aIndexes.push(i);
            a_count++;
        } else {
            bIndexes.push(i);
            b_count++;
        }
    }

    if (a_count % 2 == 1 && b_count % 2 == 1) {
        cout << -1;
        return 0;
    }

    int id;
    for (int i = 0; i < n / 2; i++) {
        if (a_count == 0 || b_count == 0)
        {
            break;
        }
        if (word[i] == word[n - i - 1] == 'a') 
        {
            a_count -= 2;
            continue;
        }
        if (word[i] == word[n - i - 1] == 'b') 
        {
            b_count -= 2;
            continue;
        }
        if (a_count == 1)
        {
            count += (n / 2) - aIndexes.top();
            break;
        }
        if (b_count == 1)
        {
            count += (n / 2) - bIndexes.top();
            break;
        }
        if (word[i] == 'a') {
            id = bIndexes.top();
            bIndexes.pop();
            aIndexes.push(id);
            count += id - i;
            word[id] = 'a';
            b_count -= 2;
        } else {
            id = aIndexes.top();
            aIndexes.pop();
            bIndexes.push(id);
            count += id - i;
            word[id] = 'b';
            a_count -= 2;
        }
    }
    cout << count;
    return 0;
}