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 <cstdio>
#include <vector>
#include <deque>
using namespace std;

char s[200009];

int biggestCount(deque<int> &q, int value) {
	int a = -1;
	int b = q.size();
	while (a + 1 < b) {
		int c = (a + b) / 2;
		if (q[c] <= value)
			a = c;
		else
			b = c;
	}
	return q.size() - b;
}

long long solve() {
	deque<int> va;
	deque<int> vb;
	for (int i=0; s[i]; ++i) {
		if ('a' == s[i]) va.push_back(i);
		else vb.push_back(i);
	}
	if (va.size() % 2 == 1)
		if (vb.size() % 2 == 1)
			return -1;

	long long res = 0;
	while (va.size() > 0 && vb.size() > 0) {
		deque<int> &x = va[0] < vb[0] ? va : vb;
		deque<int> &y = va[0] < vb[0] ? vb : va;
		if (x.size() == 1) {
			res += y.size() / 2;
			break;
		}
		res += biggestCount(y, x.back());
		x.pop_front();
		x.pop_back();
	}
	return res;
}

int main() {
	scanf("%s", s);
	long long res = solve();
	printf("%lld\n", res);
	return 0;
}