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<bits/stdc++.h>
#include<tr1/unordered_map>
#define lowbit(x) (x&-x)
#define pb push_back
#define pii pair<int,int>
#define SZ(x) (int)x.size()
#ifdef __linux__
#define getchar getchar_unlocked
#endif
#define mem(a,b) memset(a,b,sizeof(a))
#define  For(i,a,b) for(int i=a,i##E=b;i<=i##E;++i)
#define rFor(i,a,b) for(int i=a,i##E=b;i>=i##E;--i)
typedef long long LL;
using namespace std;
const int N=200010;
const int inf=0x3f3f3f3f;
template<typename T>inline bool chkmin(T &a,const T &b){return a>b?a=b,1:0;}
template<typename T>inline bool chkmax(T &a,const T &b){return a<b?a=b,1:0;}
template<typename T>inline void read(T &x)
{
	x=0;int _f(0);char ch=getchar();
	while(!isdigit(ch))_f|=(ch=='-'),ch=getchar();
	while( isdigit(ch))x=x*10+ch-'0',ch=getchar();
	x=_f?-x:x;
}
inline void file()
{
#ifdef ztzshiwo
	freopen("in.txt","r",stdin);
	freopen("out.txt","w",stdout);
#endif
}
int n,t[N],cnt,tot;
LL ans;
char s[N];
vector<int>G[26];
struct node
{
	int l,r;
	node(){}
	node(int l,int r):l(l),r(r){}
}a[N];
inline bool operator<(const node&A,const node&B){return A.l<B.l;}
inline void add(int x){for(;x<=n;x+=lowbit(x))t[x]++;}
inline int sum(int x){int r=0;for(;x;x-=lowbit(x))r+=t[x];return r;}
int main()
{
	file();
	scanf("%s",s+1);
	n=strlen(s+1);
	For(i,1,n)G[s[i]-'a'].pb(i);
	For(i,0,25)
	{
		if(SZ(G[i])&1)cnt++;
		int l=0,r=SZ(G[i])-1;
		while(l<r)a[++tot]=node(G[i][l],G[i][r]),l++,r--;
	}
	if(cnt>(n&1)){puts("-1");exit(0);}
	sort(a+1,a+tot+1);
	For(i,1,tot)
	{
		ans+=n-i+1-a[i].r+sum(a[i].r);
		add(a[i].r);
	}
	printf("%lld\n",ans);
	return 0;
}