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
#include <stdio.h>
#include <string.h>

#include <utility>

int findNext(char* data, int n, char c, int position) {
  position++;
  while (position < n && data[position] != c) {
    position++;
  }
  return position;
}

int main() {
  long long int moves = 0;
  char data[200001];
  scanf("%s", data);
  const int n = strlen(data);
  int a = findNext(data, n, 'a', -1);
  int b = findNext(data, n, 'b', -1);
  for (int i = 0; i < n / 2; ++i) {
    const auto j = n - i - 1;
    if (data[i] != data[j]) {
      if (data[i] == 'a') {
        if (b <= i) b = findNext(data, n, 'b', i);
        if (j == b && n % 2 == 1) {
          moves += b - n / 2;
          break;
        } else if (j <= b) {
          moves = -1;
          break;
        } else {
          std::swap(data[i], data[b]);
          moves += b - i;
          b = findNext(data, n, 'b', b);
        }
      } else {
        if (a <= i) a = findNext(data, n, 'a', i);
        if (j == a && n % 2 == 1) {
          moves += a - n / 2;
          break;
        } else if (j <= a) {
          moves = -1;
          break;
        } else {
          std::swap(data[i], data[a]);
          moves += a - i;
          a = findNext(data, n, 'a', a);
        }
      }
    }
  }
  printf("%lld\n", moves);
  return 0;
}