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 <iostream> 
#include <string>
#include <vector>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <functional>

using namespace std;
using ll = long long;

const ll INF = 1e9;
const ll MOD = 1e9 + 7;
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };

int main()
{
	string s, ss, t;
	map<string, int> m;
	int i, j, c = 0, count = 0;

	cin >> s;
	for (i = 0; i < s.size(); i++) {
		ss = s[i];
		m[ss]++;
	}

	for (auto x : m) {
		if (x.second % 2 == 1) {
			count++;
		}
	}

	if (count >= 2) {
		cout << "-1" << endl;
	}
	else {
		for (i = 0; i < s.size() / 2; i++) {
			for (j = s.size() - i - 1; j > i; j--) {
				if (s[i] == s[j]) {
					t = s[j];
					s.erase(s.begin() + j);
					s.insert(s.size() - i, t);
					c += s.size() - i - 1 - j;
					break;
				}
			}
		}

		cout << c << endl;
	}
}