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 <bits/stdc++.h>

using namespace std;

#define ll long long

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);
    cout.tie(NULL);
    
    string s; cin>>s;

    ll n=s.size(), ans=0;
    if (n&1) {
        vector<int> a, b;
        for (int i=0; i<n; ++i) {
            if (s[i] == 'a') a.push_back(i);
            else b.push_back(i);
        }

        if (a.size()&1) a.swap(b);
        for (int i=0; i<(int)a.size()/2; ++i) {
            int l=a[i], r=a[(int)a.size()-1-i];
            ans+=abs(r-(n-l-1));
        }
    } else {
        vector<int> v;
        for (int i=0; i<n; ++i) {
            if (s[i] == 'b') v.push_back(i);
        }

        if (v.size()&1) {
            ans=-1;
        } else {
            for (int i=0; i<(int)v.size()/2; ++i) {
                int l=v[i], r=v[(int)v.size()-1-i];
                ans+=abs(r-(n-l-1));
            }
        }
    }

    cout<<ans<<"\n";
}