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 Java8 (OpenJDK 1.8.0) (judge verdict: Time Limit Exceeded)


 
import java.util.LinkedList;
import java.util.Scanner;
class Main{
	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		while(scan.hasNextLine()){
		String s=new String();
		boolean judge;
		int length,cnt,cnte,cnto,temp,index;
		int[] kinds=new int[26];
		LinkedList<Integer> L=new LinkedList<Integer>();
		s=scan.nextLine();
		judge= true;
		length=s.length();
		cnt=cnte=cnto=0;
		for(int i=0;i<length;i++){
			temp=s.charAt(i)-'a';
			L.add(temp);
			kinds[temp]++;
		}
		for(int i=0;i<26;i++){
			if(kinds[i]==0)
				continue;
			if(kinds[i]==length){
				judge=false;
				break;
			}
			if(kinds[i]%2==1)
				cnto++;
			else
				cnte++;
		}
		//System.out.println(cnte+" "+cnto+" "+L.get(0)+" "+L.size());
		if(length==1||!judge){
			System.out.println("0");
		}
		else if((length%2==1&&cnte!=0&&cnto<=1)||(length%2==0&&cnto==0)){
			while(L.size()!=0){
				judge=true;
				for(int j=L.size()-1;j>0;j--){
					if(L.get(j)==L.getFirst()){
						cnt+=L.size()-1-j;
						L.remove(j);
						judge=false;
						break;
					}
				}
				L.removeFirst();
				if(judge){
					cnt+=L.size()/2;
				}
			}
			System.out.println(cnt);
		}
		else
			System.out.println("-1");
	}
	}
}