S = list(input().strip()) n = len(S) def quick_test(S): n = len(S) A = sum(x == 'a' for x in S) B = n - A if n % 2 == 0: return A % 2 == 0 and B % 2 == 0 else: return (A % 2 == 0) ^ (B % 2 == 0) def aux(S, a, b): acc = 0 i = a j = b while True: if a == b: return acc if a + 1 == b: return acc + (S[a] != S[b]) if S[a] == S[b]: a = a+1 b = b-1 continue x = S[a] for i in range(max(a, i), b+1): if S[i] != x: break x = S[b] for j in range(min(b, j), a-1, -1): if S[j] != x: break if (i - a) < (b - j): # A ma blizej S[a], S[i] = S[i], S[a] else: S[b], S[j] = S[j], S[b] acc += min(i-a, b-j) a = a+1 b = b-1 def main(S): return aux(S, 0, len(S) - 1) if not quick_test(S): print("-1") else: print(main(S))
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 | S = list(input().strip()) n = len(S) def quick_test(S): n = len(S) A = sum(x == 'a' for x in S) B = n - A if n % 2 == 0: return A % 2 == 0 and B % 2 == 0 else: return (A % 2 == 0) ^ (B % 2 == 0) def aux(S, a, b): acc = 0 i = a j = b while True: if a == b: return acc if a + 1 == b: return acc + (S[a] != S[b]) if S[a] == S[b]: a = a+1 b = b-1 continue x = S[a] for i in range(max(a, i), b+1): if S[i] != x: break x = S[b] for j in range(min(b, j), a-1, -1): if S[j] != x: break if (i - a) < (b - j): # A ma blizej S[a], S[i] = S[i], S[a] else: S[b], S[j] = S[j], S[b] acc += min(i-a, b-j) a = a+1 b = b-1 def main(S): return aux(S, 0, len(S) - 1) if not quick_test(S): print("-1") else: print(main(S)) |