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
#include <iostream>
#include <string>
#include <algorithm>

int main() {
	std::string palindrom;
	std::cin >> palindrom;
	long long count{};
	if (palindrom.size() == 1) {
		std::cout << 0 << std::endl;
		return 0;
	} else if (palindrom.size() == 2) {
		std::cout << ((palindrom[0] == palindrom[1]) ? "0" : "-1") << std::endl;
		return 0;
	}
	int numberOfA = std::count_if(palindrom.begin(), palindrom.end(), [](auto c) {
		return c == 'a';
		});
	int numberOfB = std::count_if(palindrom.begin(), palindrom.end(), [](auto c) {
		return c == 'b';
		});
	if (palindrom.size() % 2 == 0 && numberOfA % 2 != 0) {
		std::cout << "-1" << std::endl;
		return 0;
	}
	long long diff{};
	for (int i = 0; i < palindrom.size() / 2; ++i) {
		if (palindrom[i] != palindrom[palindrom.size() - i - 1]) {
			if (palindrom[i] == 'a') {
				++diff;
			} else {
				--diff;
			}
		}
		count += abs(diff);
	}
	if (palindrom.size() % 2 == 0  && count > 2) {
		count = count - (abs(diff) / 2);
	}
	std::cout << count << std::endl;

	return 0;
}