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: Accepted)

#include<cstdio>
#include<cstring>
#include<vector>
#include<iostream>
#include<algorithm>
#define pb push_back
#define lowbit(x) ((x)&(-(x)))
using namespace std;
char s[200010];
int n, c[200010], a[200010];
long long ans;
vector < int > p[26];
bool check() {
	int cnt = 0;
	for (int i = 0; i < 26; ++i)
		cnt += p[i].size() & 1;
	return cnt < 2;
}
void add(int p, int x) {
	for (; p <= n; p += lowbit(p)) c[p] += x;
}
int sum(int p) {
	int res = 0;
	for (; p; p -= lowbit(p)) res += c[p];
	return res;
}
int main() {
	scanf("%s", s + 1);
	n = strlen(s + 1);
	for (int i = 1; i <= n; ++i) p[s[i]-'a'].pb(i);
	if (!check()) return puts("-1"), 0;
	for (int i, sz, x = 0; x < 26; ++x) {
		for (i = 0; i < (sz = p[x].size()); ++i)
			a[p[x][i]] = p[x][sz-1-i];
	}
	for (int i = 1; i <= n; ++i)
		ans += sum(a[i]), add(a[i], 1);
	printf("%lld\n", ans / 2);
	return 0;	
}