Problem:
Score : 800 points

Problem Statement

You are given a string S consisting of lowercase English letters.
Determine whether we can turn S into a palindrome by repeating the operation of swapping two adjacent characters. If it is possible, find the minimum required number of operations.

Constraints

1 \leq |S| \leq 2 × 10^5

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If we cannot turn S into a palindrome, print -1. Otherwise, print the minimum required number of operations.

Sample Input 1

eel

Sample Output 1

1

We can turn S into a palindrome by the following operation:

Swap the 2-nd and 3-rd characters. S is now ele.

Sample Input 2

ataatmma

Sample Output 2

4

We can turn S into a palindrome by the following operation:

Swap the 5-th and 6-th characters. S is now ataamtma.

Swap the 4-th and 5-th characters. S is now atamatma.

Swap the 3-rd and 4-th characters. S is now atmaatma.

Swap the 2-nd and 3-rd characters. S is now amtaatma.

Sample Input 3

snuke

Sample Output 3

-1

We cannot turn S into a palindrome.

Solution in PyPy3 (2.4.0) (judge verdict: Wrong Answer)

s=input()
n=len(s)
l=[[] for i in range(26)]
No=2**18
tree=[0]*(2*No)
for i in range(No-1,No-1+n):
    tree[i]=1
for i in range(No-2,-1,-1):
    tree[i]=tree[i*2+1]+tree[i*2+2]
#kにxを加える(0index)
def add(k,x):
    k+=No-1
    while k>=0:
        tree[k]+=x
        k=(k-1)//2
#lからrまでの和(l,r含む)
def query(l,r):
    L=l+No-1
    R=r+No-1
    s=0
    while L<=R:
        if R&1:
            s+=tree[R]
            R-=2
        else:
            R-=1
        if L&1:
            L-=1
        else:
            s+=tree[L]
        L>>=1;R>>=1
    return s
for i,c in enumerate(s):
    l[ord(c)-97].append(i)
mid=-1
for i in range(26):
    if len(l[i])%2==1:
        if mid!=-1:
            print(-1)
            quit()
        else:
            mid=i
ans=0
i=0
mid=n
while i<=n:
    if tree[i+No-1]==0:
        i+=1
        continue
    t=l[ord(s[i])-97].pop()
    if len(l[ord(s[i])-97])==0:
        mid=t
        add(t,-1)
        i+=1
        continue
    add(t,-1)
    ans+=query(t,n)
    i+=1
ans+=query(mid,n)
print(ans)