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
#include <cstdio>
#include <cstdint>
#include <vector>

int main () {
	char c;
	std::vector<bool> word;
	int as = 0;
	int bs = 0;
	while (true) {
		scanf("%c", &c);
		if (c == 'a') {
			word.push_back(false);
			as++;
		}
		else if (c == 'b') {
			word.push_back(true);
			bs++;
		}
		else {
			break;
		}
	}
	if (((as % 2) == 1) && ((bs % 2) == 1)) {
		printf("-1\n");
		return 0;
	}
	if ((as == 0) || (bs == 0)) {
		printf("0\n");
		return 0;
	}
	int64_t moves = 0;
	int n = word.size();
	int next_a = -1;
	int next_b = -1;
	for (int i = 0; i < n; ++i) {
		if ((!word[i]) && (next_a == -1)) {
			next_a = i;
		}
		if ((word[i]) && (next_b == -1)) {
			next_b = i;
		}
		if ((next_a >= 0) && (next_b >= 0)) {
			break;
		}
	}
	for (int i = 0; i < n / 2; ++i) {
		if ((next_a < i) || (word[next_a])) {
			for (int j = next_a + 1; j < n; ++j) {
				if (!word[j]) {
					next_a = j;
					break;
				}
			}
		}
		if ((next_b < i) || (!word[next_b])) {
			for (int j = next_b + 1; j < n; ++j) {
				if (word[j]) {
					next_b = j;
					break;
				}
			}
		}
		if (word[i] == word[n - 1 - i]) {
			continue;
		}
		if (word[i]) {
			if (next_a == n - 1 - i) {
				moves += (next_a - i) / 2;
				break;
			}
			moves += next_a - i;
			word[i] = false;
			word[next_a] = true;
		}
		else {
			if (next_b == n - 1 - i) {
				moves += (next_b - i) / 2;
				break;
			}
			moves += next_b - i;
			word[i] = true;
			word[next_b] = false;
		}
	}
	printf("%lld\n", moves);
	return 0;
}