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
105
106
#include <iostream>
#include <string.h>
using namespace std;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    char w[200001];
    cin >> w;

    int len, len2, na, nb;
	long long int res;
	char ca, cb, tc;
	len = strlen(w);
	len2 = len / 2;
	res = 0;

    na = -1;
	for (int i = 1; i < len; i++) {
		if (w[i] != w[0]) {
			na = i;
			break;
		}
	}
	if (na == -1) {
		cout << "0\n";
		return 0;
	}
	
	for (int i = len - 2; i >= 0; i--) {
		if (w[len - 1] != w[i]) {
			nb = i;
			break;
		}
	}

	for (int i = 0; i < len2; i++) {
		// cout << "START I:" << i << " NA:" << na << " NB:" << nb << "\n";
		// cout << w << "\n";
		ca = w[i];
		cb = w[len - i - 1];
		if (ca != cb) {
			if (i == len - i - 2) {
                cout << "-1\n";
				return 0;
			}
			
			if (na <= i) {
				for (na = i + 1; na < len; na++) {
					if (w[i] != w[na]) {
						break;
					}
				}
			}
			
			if (nb >= len - i - 1) {
				for (nb = len - i - 2; nb >= 0; nb--) {
					if (w[len - i - 1] != w[nb]) {
						break;
					}
				}
			}
			
			if (na - i < (len - i - 1) - nb) {
				res = res + na - i;
				tc = w[i];
				w[i] = w[na];
				w[na] = tc;
				if (na > nb) {
					nb++;
				}
				if (na > i + 1) {
					for (int j = na + 1; j < len; j++) {
						if (w[na] != w[j]) {
							na = j;
							break;
						}
					}
				}
			} else {
				res = res + (len - i - 1) - nb;
				tc = w[len - i - 1];
				w[len - i - 1] = w[nb];
				w[nb] = tc;
				if (nb < na) {
					na--;
				}
				if (nb < len - i - 2) {
					for (int j = nb - 1; j >= 0; j--) {
						if (w[nb] != w[j]) {
							nb = j;
							break;
						}
					}
				}
			}
		}
		
		// cout << "I:" << i << " R:" << res << " | " << w << "\n";
	}

    cout << res << "\n";

    return 0;
}