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
//GRT_2018
#include <bits/stdc++.h>
#define PB push_back
#define ST first
#define ND second
//mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count());

using namespace std;

using ll = long long;
using pi = pair<int,int>;
using vi = vector<int>;

const int nax = 200 * 1000 + 10;
string s;
int val[nax];
vi a, b;
int cnt[5];

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cin >> s;
	for (int i = 0; i < (int)s.size(); ++i) {
		if (s[i] == 'a') a.PB(i);
		else b.PB(i);
	}
	if (((int)a.size() & 1) && ((int)b.size() & 1)) {
		cout << "-1";
		return 0;
	}
	for (int i = 0; i < (int)a.size() / 2; ++i) {
		val[a[i]] = -1;
		val[a[(int)a.size() - i - 1]] = 1;
	}
	for (int i = 0; i < (int)b.size() / 2; ++i) {
		val[b[i]] = -1;
		val[b[(int)b.size() - i - 1]] = 1;
	}
	ll inv = 0;
	string h1 = "", h2 = "";
	for (int i = 0; i < (int)s.size(); ++i) {
		for (int x = 1; x > val[i]; --x) {
			inv += cnt[x + 1];
		}
		cnt[val[i] + 1]++;
		if (val[i] == -1) h1 += s[i];
		else if (val[i] == 1) h2 += s[i];
	}
	reverse(h2.begin(), h2.end());
	int cntA = 0, cntA2 = 0, ptr = 0;
	for (int i = 0; i < (int)h1.size(); ++i) {
		if (h1[i] == 'a') cntA++;
		else {
			while (ptr < (int)h2.size() && h2[ptr] == 'a') {
				ptr++;
				cntA2++;
			}
			inv += abs(cntA - cntA2);
			ptr++;
		}	
	}
	cout << inv;
}