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;

namespace {

#define VERA(i, a, b)for(auto i=(ll)(a);i<(ll)(b);++i)
#define ANDY(i, a, b)for(auto i=(ll)(a);i>(ll)(b);--i)

typedef long long ll;
typedef double dd;

template <class T> inline ll Size(const T& x) { return x.size(); }

string str;
vector<ll> pos[26];

void Solve(ll test_num) {
  (void) test_num;
  VERA(i, 0, Size(str)) {
    pos[str[i] - 'a'].push_back(i);
  }
  ll odd = 0;
  for (const auto& p : pos)
    if (Size(p) % 2 == 1)
      ++odd;
  if (odd > 1) {
    cout << "-1\n";
    return;
  }
  vector<pair<ll, ll>> segs;
  VERA(c, 0, 26) {
    VERA(i, 0, Size(pos[c]) / 2) {
      segs.emplace_back(pos[c][i], pos[c][Size(pos[c]) - i - 1]);
    }
  }
  sort(segs.begin(), segs.end());
  ll res = 0;
  ll diff = Size(str) - 1;
  for (const auto& seg : segs) {
    res += diff - (seg.second - seg.first);
    diff -= 2;
  }
  cout << res << endl;
}

bool Input() {
  if (not(cin >> str))
    return false;
  VERA(c, 0, 26) pos[c].clear();
  return true;
}

void Init() {
}

}

int main() {
#ifdef AZN
  const auto start_time = chrono::system_clock::now();
  freopen("../input.txt", "r", stdin);
#endif
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  srand(1223);
  Init();
  ll test = 1;
  while (Input()) {
    Solve(test++);
  }
#ifdef AZN
  cerr << "Took: " << ((chrono::system_clock::now() - start_time).count() /
                       static_cast<double>(chrono::system_clock::period::den)) << " s" << endl;
#endif
  return 0;
}