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 Ruby (2.3.3) (judge verdict: Accepted)

class BIT
    def initialize(n)
        @n = n+1
        @dat = Array.new(@n+1, 0)
    end

    def sum(i)
        s = 0
        while i >= 0 do
            s += @dat[i]
            i = (i & (i + 1)) - 1
        end
        s
    end

    def add(i, x)
        while i <= @n do
            @dat[i] += x
            i |= i + 1
        end
    end
end

S = gets.chomp
L = S.length
total = Hash.new(0)
L.times do |i|
    total[S[i]] += 1
end
if total.values.count{|v|v%2==1} > 1
    puts -1
    exit
end
center = total.keys.find{|k|total[k]%2==1}

now = Hash.new(0)
left = ''
L.times do |i|
    if now[S[i]] < total[S[i]]/2
        left << S[i]
    end
    now[S[i]] += 1
end

lpos = {}
rpos = {}
left.length.times do |i|
    lpos[left[i]] ||= []
    rpos[left[i]] ||= []
    lpos[left[i]].push(i)
    rpos[left[i]].unshift(L-1-i)
end
if center
    lpos[center] ||= []
    lpos[center].push(L/2)
end

order = []
L.times do |i|
    if lpos[S[i]].length > 0
        order[i] = lpos[S[i]].shift
    else
        order[i] = rpos[S[i]].shift
    end
end

ans = 0
bit = BIT.new(order.length)
order.length.times do |i|
    ans += i - bit.sum(order[i])
    bit.add(order[i], 1)
end
puts ans