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>
using namespace std;
typedef  long long ll;
int const N = 202000;
char s[N];
deque<int>nex[26];
bool vis[N];
vector<int>ans;
int seg[N*4] , k;
int get(int node , int start , int end){
	if(end < k)return 0;
	if(start >= k)return seg[node];
	int mid = (start+end)/2;
	return get(node*2,start,mid) + get(node*2+1,mid+1,end);
}
int up(int node , int start , int end){
	if(start==end)seg[node] = 1;
	else{
		int mid = (start+end)/2;
		if(mid >= k)up(node*2,start,mid);
		else up(node*2+1,mid+1,end);
		seg[node] = seg[node*2] + seg[node*2+1];
	}
}
int main()
{
	
	scanf("%s",s);
	int len = strlen(s);
	int frq[26];
	memset(frq,0,sizeof frq);
	for(int i = 0 ; i < len ; i++){
		nex[s[i]-'a'].push_back(i);
		frq[s[i]-'a']++;	
	}
	bool odd = 0;
	for(int i = 0 ; i < 26 ; i++){
		if(frq[i]%2==1)if(!odd)odd = 1;else {puts("-1");return 0;}
	}
	string s1 = "";
	int l = 0 , r = len-1;
	ans.resize(len);
	for(int i = 0 ; i < len ; i++){
		if(vis[i])continue;
		if(frq[s[i]-'a']<=1)continue;
		ans[l] = nex[s[i]-'a'].front()+1;
		ans[r] = nex[s[i]-'a'].back()+1;
		vis[ans[r]] = 1;
		nex[s[i]-'a'].pop_back();
		nex[s[i]-'a'].pop_front();
		l++;
		r--;
		frq[s[i]-'a']-=2;
	}
	if(odd)for(int i = 0 ; i < 26 ; i++)
		if(frq[i]==1)ans[l] = nex[i].front()+1;
	ll res = 0;
	for(int i = 0 ; i < len ; i++){
		k = ans[i];
		res += get(1,1,len);
		up(1,1,len);
	}
	printf("%d\n", res);
	return 0;

}