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<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
#define rep(N) for (int i = 0; i < N; ++i)
#define For(i, N) for (i = 0; i < N; ++i)
#define re return 0;

using namespace std;
using ll = long long int;
using vi = vector<int>;
using vvi = vector<vector<int>>;

int main() {
	int i;
	vi v;
	int vSize = 26;
	int ans = 0;
	int count = 0;
	int ostracized;
	bool flag;
	string s;
	cin >> s;

	rep(vSize)v.push_back(0);
	for (char a : s)++v[a - 'a'];
	For(i, vSize)if (v[i] % 2 != 0) {
		++count;
		ostracized = i;
	}
	if (count >= 2) {
		cout << "-1" << endl;
		re
	}
	if (count == 1) {
		char a = 'a' + ostracized;
		int c = 0;
		for (i = 0; c < v[ostracized] / 2 + 1; ++i) {
			if (s[i] == a)++c;
		}
		if (i < s.size())flag = false;
		else flag = true;
	}

	if (count == 0 || flag) {
		while (!s.empty() || s.begin() != s.end()) {
			int x = s.find_first_of(s.back());
			s.pop_back();
			s.erase(x, 1);
			ans += x;
		}
	}
	else while (s.begin() != s.end()) {
		int x = s.find_last_of(s.front());
		s.erase(0, 1);
		s.erase(x, 1);
		ans += s.size() - x;
	}
	cout << ans << endl;
	re
}