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
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <queue>
#include <string>
using namespace std;

long long a, b, len, result;
bool word[200000];

int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	string _word;
	cin >> _word;
	len = _word.size();
	for (int i = 0; i < len; i++) {
		if (_word[i] == 'a')
			a++;
		else
			b++;
	}
	if (a % 2 == 1 && b % 2 == 1) {
		cout << -1;
		return 0;
	}
	bool avalue = 0;
	if (b % 2 == 1 || a > b)
		avalue = 1;
	for (int i = 0; i < len; i++) {
		if (_word[i] == 'a')
			word[i] = avalue;
		else
			word[i] = !avalue;
	}
	int left1 = 0, right1 = 0;
	for (int i = 0; i < len / 2; i++)
		left1 += word[i];
	for (int i = len - len / 2; i < len; i++)
		right1 += word[i];
	if (left1 < right1) {
		int left = len / 2 - 1, right = len - len / 2;
		right1 = (right1 - left1) / 2;
		for (; right1; right1--) {
			while (word[left])
				left--;
			while (!word[right])
				right++;
			result += (right - left);
			word[left] = 1;
			word[right] = 0;
		}
		if (len % 2 == 1 && word[len / 2] == 1) {
			while (word[left])
				left--;
			result += (len / 2 - left);
			word[left] = 1;
			word[len / 2] = 0;
		}
	}
	else if (left1 > right1) {
		int left = len / 2 - 1, right = len - len / 2;
		right1 = (left1 - right1) / 2;
		for (; right1; right1--) {
			while (!word[left])
				left--;
			while (word[right])
				right++;
			result += (right - left);
			word[left] = 0;
			word[right] = 1;
		}
		if (len % 2 == 1 && word[len / 2] == 1) {
			while (word[right])
				right++;
			result += (right - len / 2);
			word[right] = 1;
			word[len / 2] = 0;
		}
	}
	int first1 = 0, first0 = 0;
	for (int i = 0; i < len / 2; i++) {
		while (word[first0])
			first0++;
		while (!word[first1])
			first1++;
		if (word[i] == 1 && word[len - i - 1] == 0) {
			result += (first0 - i);
			word[i] = 0;
			word[first0] = 1;
		}
		else if (word[i] == 0 && word[len - i - 1] == 1) {
			result += (first1 - i);
			word[i] = 1;
			word[first1] = 0;
		}
		first1 = max(first1, i);
		first0 = max(first0, i);
	}
	cout << result;
}