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
def main():
    pal = list(input())
    if not is_pal(pal):
        print(-1)
    else:
        print(palin(pal, 0, len(pal)-1))

def is_pal(pal):
    if len(pal)%2 == 1:
        return(True)
    else:
        a = 0
        b = 0
        for i in pal:
            if i == 'a':
                a+=1
            else:
                b+=1
        return(a%2==0)

def palin(pal, l, p):
    wyn = 0
    opp = len(pal)
    oll = 0
    while l<p:
        while l<p and pal[l] == pal[p]:
            l+=1
            p-=1
        if l>=p:
            break
        ll = max(l+1, oll-1)
        pp = min(p-1, opp+1)
#        ll = max(l+1, 0)
#        pp = min(p-1, len(pal))
        while pal[ll] == pal[l] and pal[pp] == pal[p]:
            ll+=1
            pp-=1
        opp = pp
        oll = ll
        if pal[pp] == pal[p]:
            pal[l], pal[ll] = pal[ll], pal[l]
            wyn+= ll-l
        else:
            pal[p], pal[pp] = pal[pp], pal[p]
            wyn+= p-pp
    return(wyn)
        
main()