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 Java7 (OpenJDK 1.7.0) (judge verdict: Wrong Answer)

import static java.lang.Math.floor;
import java.util.Scanner;
public class Main {
        static Scanner scanner = new Scanner(System.in);
        static String S = scanner.next();
        static char[] chArray = S.toCharArray();  
        static int cnt;
        public static void main(String[] args) {
           
            cnt = 0;
            int Slen = S.length();
            for (int i=0; i < (int)floor(Slen/2); i++){
                int j=i+1;
                Boolean match = false;
                int n=0;
                while (j < S.length()){
                    if (chArray[i] == chArray[j]){
                        n= j;
                        match = true;
                    }
                    j++;
                }
                if (match){
                    int k=Slen-i-1;
                    if (j < k) bubble(j-1,k-1);
                    else bubble(k-1, j-1);
                } else {
                    cnt = -1;
                    break;
                }
            }
            System.out.println(cnt);
        };
        
    static private void bubble(int i,int j){
        if (i==j) return;
        for (int k=i; k<j; k++){
            char c;
            c=chArray[k];
            chArray[k]=chArray[k+1];
            chArray[k+1]=c;
            cnt++;
        }
    }
}