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 int int_fast64_t

int next_power_of_two(int n) {
  int p = 1;
  while (p <= n)
    p *= 2;
  return p;
}

struct fenwick {
  int n;
  vector<int> d;
  fenwick(int n) : n(next_power_of_two(n)), d(this->n) {}

  int query(int i) {
    int s=0;
    for (++i; i; i -= i&-i)
      s += d[i];
    return s;
  }

  void incr(int i) {
    for (++i; i < n; i += i&-i)
      d[i] += 1;
  }
};

int solve(string const& s) {
  array<int, 'z'-'a'+1> count = {};
  for (char c : s) ++count[c-'a'];

  array<int, 'z'-'a'+1> lefties = {};
  char single = '\0';
  for (size_t i=0; i<count.size(); ++i) {
    lefties[i] = count[i]/2;
    if (count[i]%2) {
      if (single)
        return -1;
      single = 'a' + i;
    }
  }
  string t;
  for (char c : s) {
    if (lefties[c - 'a']) {
      --lefties[c - 'a'];
      t.push_back(c);
    }
  }
  {
    string t_cpy = t;
    if (single)
      t.push_back(single);
    t.insert(t.end(), t_cpy.rbegin(), t_cpy.rend());
  }
  cout << s << '\n' << t << '\n' << flush;

  array<vector<int>, 'z'-'a'+1> positions = {};
  array<int, 'z'-'a'+1> position_index = {};
  for (size_t i=0; i<s.size(); ++i)
    positions[s[i]-'a'].push_back(i);

  vector<int> perm;
  for (char c : t)
    perm.push_back(positions[c-'a'][position_index[c-'a']++]);

  int ops = 0;
  fenwick ft(perm.size());
  for (size_t i=0; i<perm.size(); ++i) {
    ops += i - ft.query(perm[i]);
    ft.incr(perm[i]);
  }
  return ops;
}

signed main() {
  ios_base::sync_with_stdio(false), cin.tie(nullptr);

  string s; cin >> s;
  cout << solve(s) << '\n';
}

/*
 * Local variables:
 * compile-command:"g++ -D_GLIBCXX_DEBUG -g3 -ggdb3 -O0 -Wall -Wextra -std=c++14 e.cc -o e && for f in *.in; do echo \"--- $f -------------\"; ./e <$f; done"
 * end:
 */