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
// PAL.cpp : Defines the entry point for the application.
//

#include <iostream>
#include <algorithm>


using namespace std;

void reverse(char& c)
{
	if (c == 'a') c = 'b';
	else c = 'a';
}

int fix(string& s, int posL)
{
	static int lA = 1;
	static int lB = 1;
	static int rA = 1;
	static int rB = 1;
	
	int posR = s.length() - 1 - posL;
	if (s[posL] == s[posR]) return 0;

	int sL = s[posL == 'a'] ? lA : lB;

	for (int i = posL+sL; i < posR; i++)
	{
		if (s[posL] != s[i]) break;
		sL++;
	}

	if (s[posL == 'a']) lA = std::max(sL - 2, 0);
	else lB = std::max(sL - 2, 0);

	int sR = s[posR == 'a'] ? rA : rB;
	for (int i = posR-sR; i > posL; i--)
	{
		if (s[posR] != s[i]) break;
		sR++;
	}

	if (s[posR == 'a']) rA = std::max(sR - 2, 0);
	else rB = std::max(sR - 2, 0);

	if (sL <= sR)
	{
		reverse(s[posL]);
		reverse(s[posL + sL]);
		return sL;
	}
	else
	{
		reverse(s[posR]);
		reverse(s[posR - sR]);
		return sR;
	}
}
int main()
{
	std::ios_base::sync_with_stdio(false);
	std::cin.tie(NULL);

	string input;
	cin >> input;

	//input = "";
	//for (int i = 0; i < 100000; i++) input += 'a';
	//for (int i = 0; i < 100000; i++) input += 'b';


	//first check
	int ca = 0;
	int cb = 0;
	for (int i = 0; i < input.length(); i++)
	{
		if (input[i] == 'a') ca++;
		else cb++;
	}
	if (ca % 2 && cb % 2)
	{
		cout << "-1";
		return 0;
	}
	
	long long seconds = 0;
	int half = input.length() / 2;
	for (int i = 0; i < half; i++)
	{
		seconds += fix(input, i);
	}

	cout << seconds;

	return 0;
}