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
#include<bits/stdc++.h>
#pragma GCC optimization("O3")
#pragma GCC optimization("unroll-loops")
#define bck(a) (a.empty() ? 0 : a.back())
using namespace std;

const int N = 1<<18;

string inp;

int solve(string s, char move){
    int n = s.length();
    int nb = count(s.begin(),s.end(),move);
    if((nb&(n-nb))&1){ return 100000000; }
    if(nb==0){return 0;}
    vector<int> poz,odl;
    for(int i = 1;i<=n;++i){
        if(s[i-1]==move){
            odl.push_back(i-1-bck(poz));
            poz.push_back(i);
        }
    }
    odl.push_back(n-bck(poz));
    int ans=0,m=odl.size();
    for(int i = 0;m-i-1>i;++i){
        while(odl[i]>odl[m-i-1]){
            --odl[i];
            ++odl[i+1];
            ++ans;
        }
        while(odl[i]<odl[m-i-1]){
            ++odl[i];
            --odl[i+1];
            ++ans;
        }
    }
    return ans;
}

int main(){

    while(true){
        int ch=getchar_unlocked();
        if(ch=='a'||ch=='b'){
            inp+=char(ch);
        }else{break;}
    }
    int ans = min(solve(inp,'b'),solve(inp,'a'));
    cout<<(ans<100000000 ? ans : -1);

    return 0;
}