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 C++14 (GCC 5.4.1) (judge verdict: Wrong Answer)

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
inline int rd(){
	char c=getchar();int x=0,flag=1;
	for(;c<'0'||c>'9';c=getchar())if(c=='-')flag=-1;
	for(;c>='0'&&c<='9';c=getchar())x=x*10+c-'0';
	return x*flag;
}
int len,sz[26]={0},nw[26]={0},c[200010],st[200010]={0},vec[26][200010];
char str[200010];bool vis[200010]={false};
inline void update(int x,int v){
	for(;x<=len;x+=x&-x)
		st[x]+=v;
	return;
}
inline int ask(int x){
	int res=0;
	for(;x;x-=x&-x)
		res+=st[x];
	return res;
}
int main(){
	scanf("%s",str+1);
	len=strlen(str+1);
	for(int i=1;i<=len;i++)
		c[i]=str[i]-'a';
	for(int i=1;i<=len;i++)
		vec[c[i]][++sz[c[i]]]=i;
	int flag=0;
	for(int i=0;i<26;i++)
		flag+=sz[i]&1;
	if(flag>1){
		puts("-1");
		return 0;
	}
	for(int i=1;i<=len;i++)
		update(i,1);
	ll ans=0;
	for(int i=1,sum=len;i<=len;i++){
		if(vis[i])
			continue;
		nw[c[i]]++;
		if(nw[c[i]]>(sz[c[i]]>>1))
			continue;
		ans+=sum-ask(vec[c[i]][sz[c[i]]-nw[c[i]]+1]);
		update(i,-1);update(vec[c[i]][sz[c[i]]-nw[c[i]]+1],-1);
		vis[i]=vis[vec[c[i]][sz[c[i]]-nw[c[i]]+1]]=false;
		sum-=2;
	}
	printf("%lld\n",ans);
	return 0;
}