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: Wrong Answer)

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 = ''
right = ''
move = 0
L.times do |i|
    if center == S[i]
        move += (L/2-i).abs
    elsif now[S[i]] < total[S[i]]/2
        move += right.length
        left << S[i]
    else
        right << S[i]
    end
    now[S[i]] += 1
end

pos = {}
left.length.times do |i|
    pos[left[i]] ||= []
    pos[left[i]] << i
end
order = []
right.reverse!
right.length.times do |i|
    order.push(pos[right[i]].shift)
end

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