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)

import sys
class BIT():
    def __init__(self,number):
        self.n=number
        self.list=[0]*(number+1)
        
    def add(self,i,x):#ith added x  1indexed
        while i<=self.n:
            self.list[i]+=x
            i+=i&-i
            
    def search(self,i):#1-i sum
        s=0
        while i>0:
            s+=self.list[i]
            i-=i&-i
        return s
    
    def suma(self,i,j):#i,i+1,..j sum
        return self.search(j)-self.search(i-1)
#from collections import defaultdict
S=input()
N = len(S)
L = 26
a = ord('a')
d = [[] for i in range(L)]
for i in range(N):
    s=ord(S[i])-a
    d[s].append(i)
flag=0
for i in range(L):
    if len(d[i])%2==1:
        flag+=1
if flag>1:
    print(-1)
    sys.exit()
Suc=[-1]*N
pairs=[]
for i in range(L):
    T=len(d[i])
    for s in range((T//2)):
        li,ri=d[i][s],d[i][-s-1]
        pairs.append((li,ri))
    if T%2==1:
        Suc[d[i][T//2]]=(N//2)+1
pairs.sort()
for i, (li,ri) in enumerate(pairs):
    Suc[li]=i+1
    Suc[ri]=N-i
Tree=BIT(N+3)
ans=0
for i in range(N):
    Tree.add(Suc[i],1)
    ans+=Tree.search(i+1)
print((N*(N+1))//2-ans)