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
#include <bits/stdc++.h>
using namespace std;
using ll = long long;


int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    set<int> apos, bpos;
    string w;
    cin >> w;
    for (int i = 0; i < size(w); ++i) {
        if (w[i] == 'a') {
            apos.insert(i);
        } else {
            bpos.insert(i);
        }
    }
    if (size(apos) & 1 && size(bpos) & 1) {
        cout << -1;
        return 0;
    }
    ll res = 0;
    for (int pos = 0; pos < size(w) / 2; ++pos) {
        if (!size(apos) || !size(bpos)) break;
        if (size(apos) == 1) {
            int p = *begin(apos);
            res += abs(p - (int)size(w) / 2);
            break;
        }
        if (size(bpos) == 1) {
            int p = *begin(bpos);
            res += abs(p - (int)size(w) / 2);
            break;
        }
        int amin = *begin(apos);
        int amax = *rbegin(apos);
        int bmin = *begin(bpos);
        int bmax = *rbegin(bpos);
        if (amin < bmin && amax > bmax) {
            apos.erase(amin);
            apos.erase(amax);
            continue;
        }
        if (amin > bmin && amax < bmax) {
            bpos.erase(bmin);
            bpos.erase(bmax);
            continue;
        }
        if (amin < bmin) {
            res += bmax - amax;
            apos.erase(amin);
            apos.erase(amax);
            bpos.erase(bmax);
            bpos.insert(amax);
        } else {
            res += amax - bmax;
            bpos.erase(bmin);
            bpos.erase(bmax);
            apos.erase(amax);
            apos.insert(bmax);
        }
    }
    cout << res;
}