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
import sys

def madrak(s0):
    d0 = len(s0)
    an = s0.count('a')
    bn = s0.count('b')
    if an == d0 or bn == d0:
        return 0
    if d0 % 2 == 0 and an % 2 == 1:
        return -1
    s = list(s0)
    i = 0
    j = d0 - 1
    dm = 0
    a = 0
    while s[a] != 'a': a += 1
    b = 0
    while s[b] != 'b': b += 1
    c = j
    while s[c] != 'a': c -= 1
    d = j
    while s[d] != 'b': d -= 1
    # print(f'{a} {b} {c} {d}')
    while i < j:
        # print(f'i={i} j={j}  a={a} b={b}  c={c} d={d}')
        if s[i] == 'a' and s[j] == 'a':
            a += 1
            while a < j and s[a] != 'a': a += 1
            if a >= j: return dm
            c -= 1
            while c > i and s[c] != 'a': c -= 1
            if c <= i: return dm
        elif s[i] == 'b' and s[j] == 'b':
            b += 1
            while b < j and s[b] != 'b': b += 1
            if b >= j: return dm
            d -= 1
            while d > i and s[d] != 'b': d -= 1
            if d <= i: return dm
        elif s[i] == 'a' and s[j] == 'b':
            if abs(a-b) <= abs(c-d):
                dm += abs(a-b)
                s[b] = 'a'
                if c == b-1: c = b
                a += 1
                b += 1
                while b < j and s[b] != 'b': b += 1
                if b >= j: return dm
                d -= 1
                while d > i and s[d] != 'b': d -= 1
                if d <= i: return dm
            else:
                dm += abs(c-d)
                s[c] = 'b'
                if b == c+1: b = c
                d -= 1
                c -= 1
                while c > i and s[c] != 'a': c -= 1
                if c <= i: return dm
                a += 1
                while a < j and s[a] != 'a': a += 1
                if a >= j: return dm
        elif s[i] == 'b' and s[j] == 'a':
            if abs(a-b) <= abs(c-d):
                dm += abs(a-b)
                s[a] = 'b'
                if d == a-1: d = a
                b += 1
                a += 1
                while a < j and s[a] != 'a': a += 1
                if a >= j: return dm
                c -= 1
                while c > i and s[c] != 'a': c -= 1
                if c <= i: return dm
            else:
                dm += abs(c-d)
                s[d] = 'a'
                if a == d+1: a = d
                c -= 1
                d -= 1
                while d > i and s[d] != 'b': d -= 1
                if d <= i: return dm
                b += 1
                while b < j and s[b] != 'b': b += 1
                if b >= j: return dm
        i += 1
        j -= 1
    return dm

s = input().strip()
print(madrak(s))