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 <memory.h>
using namespace std;
typedef long long LL;
const int MAXN = 2e5 + 10;
string s;
int cnt[26], pre[MAXN], key = -1;
vector<int> nums;
int tree[MAXN], n;
inline int lowbit(int i) {
    return i&(-i);
}
void add (int i) {
    while (i <= n) {
        tree[i]++;
        i += lowbit(i);
    }
}
int sum (int i) {
    int ret = 0;
    while (i > 0) {
        ret += tree[i];
        i -= lowbit(i);
    }
    return ret;
}

void check() {
    for (char c : s) cnt[c-'a']++;
    int flag = 0;
    for (int i = 0; i < 26; i++) {
        if (cnt[i] % 2 != 0) flag++;
    }
    if (flag > 1) {
        cout << -1 << endl;
        exit(0);
    }
}
void solve() {
    memset(pre, -1, sizeof(pre));
    memset(cnt, -1, sizeof(cnt));
    for (int i = 0; i < s.size(); i++) {
        pre[i] = cnt[s[i]-'a'];
        cnt[s[i]-'a'] = i;
    }
    for (int i = 0; i < s.size(); i++) {
        if (i < cnt[s[i]-'a']) {
            nums.push_back(s.size() - cnt[s[i]-'a']);
            if (nums.back() >= n / 2) nums.back()++;
            cnt[s[i]-'a'] = pre[cnt[s[i]-'a']];
        }
        else if (i == cnt[s[i] - 'a']) {
            key = nums.size();
            nums.push_back(n / 2);
        }
    }
}
int main() {
//    freopen("test.txt", "r", stdin);
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    cin >> s;
    n = s.size() + 1;
    check();
    solve();
    LL ret = 0;
    for (int i = 0; i < nums.size(); i++) {
        int num = nums[i];
        add (num);
        int val = (sum(n) - sum(num));
        if (i == key) ret += val;
        else ret += 2*val;
        if (i > key && num < nums[key]) ret--;

    }
    cout << ret << endl;
    return 0;
}