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;

#define N 120000

int n,ans,cnt[200],c[200][N],a[N],bit[N];
char s[N],s1[N],s2[N];

void add(int x){for (int i=x;i<=n;i+=i&(-i)) bit[i]++;}

int qry(int x){int ret=0; for (int i=x;i;i-=i&(-i)) ret+=bit[i]; return ret;}

int main(){
    scanf("%s",s+1); n=strlen(s+1);
    for (int i=1;i<=n;i++) cnt[s[i]]++;
    bool fl=!(n&1);
    for (int i='a';i<='z';i++) if (cnt[i]&1){if (fl){puts("-1"); return 0;} fl=1;}
    char ch='?'; for (int i='a';i<='z';i++){if (cnt[i]&1) ch=i; ++cnt[i]/=2;}
    int xb=0,xb2=0;
    for (int i=1;i<=n;i++)
        if (cnt[s[i]]>0){
            if (ch==s[i] && cnt[s[i]]==1){ ans+=i-(xb+1)+(n+1)/2-(xb+1); cnt[s[i]]--;}
            else{cnt[s[i]]--; s1[++xb]=s[i]; ans+=i-xb;}
        }
        else s2[++xb2]=s[i];
    memset(cnt,0,sizeof cnt);
    for (int i=1;i<=xb;i++) c[s1[i]][++cnt[s1[i]]]=xb-i+1;
    memset(cnt,0,sizeof cnt);
    for (int i=xb;i>=1;i--) a[i]=c[s2[i]][++cnt[s2[i]]];
    for (int i=1;i<=xb;i++){
        ans+=qry(n)-qry(a[i]); add(a[i]);
    }
    printf("%d\n",ans);

    return 0;
}