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 Rust (1.15.1) (judge verdict: Accepted)

macro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; input_inner ! { iter , $ ( $ r ) * } } ; ( iter = $ iter : ident , $ ( $ r : tt ) * ) => { let s = { use std :: io :: Read ; let mut s = String :: new ( ) ; std :: io :: stdin ( ) . read_to_string ( & mut s ) . unwrap ( ) ; s } ; let mut $ iter = s . split_whitespace ( ) ; input_inner ! { $ iter , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let s = { use std :: io :: Read ; let mut s = String :: new ( ) ; std :: io :: stdin ( ) . read_to_string ( & mut s ) . unwrap ( ) ; s } ; let mut iter = s . split_whitespace ( ) ; input_inner ! { iter , $ ( $ r ) * } } ; }
macro_rules ! input_inner { ( $ iter : expr ) => { } ; ( $ iter : expr , ) => { } ; ( $ iter : expr , mut $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let mut $ var = read_value ! ( $ iter , $ t ) ; input_inner ! { $ iter $ ( $ r ) * } } ; ( $ iter : expr , mut $ var : ident $ ( $ r : tt ) * ) => { input_inner ! { $ iter , mut $ var : usize $ ( $ r ) * } } ; ( $ iter : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ iter , $ t ) ; input_inner ! { $ iter $ ( $ r ) * } } ; ( $ iter : expr , $ var : ident $ ( $ r : tt ) * ) => { input_inner ! { $ iter , $ var : usize $ ( $ r ) * } } ; }
macro_rules ! read_value { ( $ iter : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ iter , $ t ) ) ,* ) } ; ( $ iter : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ iter , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ iter : expr , { chars : $ base : expr } ) => { read_value ! ( $ iter , String ) . chars ( ) . map ( | c | ( c as u8 - $ base as u8 ) as usize ) . collect ::< Vec < usize >> ( ) } ; ( $ iter : expr , { char : $ base : expr } ) => { read_value ! ( $ iter , { chars : $ base } ) [ 0 ] } ; ( $ iter : expr , chars ) => { read_value ! ( $ iter , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ iter : expr , char ) => { read_value ! ( $ iter , chars ) [ 0 ] } ; ( $ iter : expr , usize1 ) => { read_value ! ( $ iter , usize ) - 1 } ; ( $ iter : expr , $ t : ty ) => { $ iter . next ( ) . unwrap ( ) . parse ::<$ t > ( ) . unwrap ( ) } ; }
#[inline]
fn rmb(k: usize) -> usize {
    (k as isize & -(k as isize)) as usize
}
pub trait Monoid {
    type T: Clone + PartialEq;
    fn mempty(&self) -> Self::T;
    fn mappend(&self, x: &Self::T, y: &Self::T) -> Self::T;
}
pub trait Group: Monoid {
    fn invert(&self, x: &Self::T) -> Self::T;
}
#[derive(Clone, Debug)]
pub struct BinaryIndexedTree<M: Monoid> {
    bit: Vec<M::T>,
    m: M,
}
impl<M: Monoid> BinaryIndexedTree<M> {
    pub fn new(n: usize, m: M) -> BinaryIndexedTree<M> {
        let bit = vec![m.mempty(); n + 1];
        BinaryIndexedTree { bit: bit, m: m }
    }
    #[doc = " 1-indexed"]
    pub fn query(&self, k: usize) -> M::T {
        let mut res = self.m.mempty();
        let mut k = k;
        while k > 0 {
            res = self.m.mappend(&res, &self.bit[k]);
            k -= rmb(k);
        }
        res
    }
    #[doc = " 1-indexed"]
    pub fn update(&mut self, k: usize, x: M::T) {
        let mut k = k;
        while k < self.bit.len() {
            self.bit[k] = self.m.mappend(&self.bit[k], &x);
            k += rmb(k);
        }
    }
}
impl<G: Group> BinaryIndexedTree<G> {
    #[doc = " 0-indexed [l, r)"]
    pub fn query_section(&self, l: usize, r: usize) -> G::T {
        self.m
            .mappend(&self.m.invert(&self.query(l)), &self.query(r))
    }
    #[doc = " 1-indexed"]
    pub fn get_val(&self, k: usize) -> G::T {
        self.query_section(k - 1, k)
    }
    #[doc = " 1-indexed"]
    pub fn set_val(&mut self, k: usize, x: G::T) {
        let y = self.m.invert(&self.get_val(k));
        let z = self.m.mappend(&y, &x);
        self.update(k, z);
    }
}
impl<M: Monoid> BinaryIndexedTree<M>
where
    M::T: Ord,
{
    #[doc = " 0-indexed"]
    pub fn lower_bound(&self, x: M::T) -> (usize, M::T) {
        let n = self.bit.len() - 1;
        let mut acc = self.m.mempty();
        let mut pos = 0;
        let mut k = 1 << format!("{:b}", n).len();
        while k > 0 {
            if k + pos <= n && self.m.mappend(&acc, &self.bit[k + pos]) < x {
                pos += k;
                acc = self.m.mappend(&acc, &self.bit[pos]);
            }
            k >>= 1;
        }
        (pos, acc)
    }
}
#[derive(Clone, Debug)]
pub struct AddGroup<T: Copy + std::ops::Add<Output = T> + std::ops::Neg<Output = T>> {
    zero: T,
}
impl<T: Copy + std::ops::Add<Output = T> + std::ops::Neg<Output = T>> AddGroup<T> {
    pub fn new(zero: T) -> AddGroup<T> {
        AddGroup { zero: zero }
    }
}
impl<T: Copy + std::ops::Add<Output = T> + std::ops::Neg<Output = T> + PartialEq> Monoid
    for AddGroup<T>
{
    type T = T;
    #[inline]
    fn mempty(&self) -> T {
        self.zero.clone()
    }
    #[inline]
    fn mappend(&self, x: &T, y: &T) -> T {
        *x + *y
    }
}
impl<T: Copy + std::ops::Add<Output = T> + std::ops::Neg<Output = T> + PartialEq> Group
    for AddGroup<T>
{
    fn invert(&self, x: &T) -> T {
        -*x
    }
}
use std::collections::VecDeque;
fn main() {
    input! { s: {chars: 'a'} };
    let n = s.len();
    let mut ans = 0;
    let mut a = (0..26).map(|_| VecDeque::new()).collect::<Vec<_>>();
    for i in 0..n {
        a[s[i]].push_back(i);
    }
    let mut odd = 0;
    for i in 0..26 {
        if a[i].len() % 2 == 1 {
            odd += 1;
        }
    }
    if n % 2 == 0 && odd > 0 || n % 2 == 1 && odd != 1 {
        println!("{}", -1);
        return;
    }
    let mut bit = BinaryIndexedTree::new(n, AddGroup::new(0i64));
    for i in 0..n {
        bit.update(i + 1, 1);
    }
    for _i in 0..n / 2 {
        let mut mj = 0;
        let mut cnt = 1_001_001_001;
        for j in 0..26 {
            if a[j].len() >= 2 {
                let l = *a[j].front().unwrap();
                let r = *a[j].back().unwrap();
                let lc = bit.query(l);
                let rc = bit.query_section(r + 1, n);
                if cnt > lc + rc {
                    cnt = lc + rc;
                    mj = j;
                }
            }
        }
        ans += cnt;
        let l = a[mj].pop_front().unwrap();
        let r = a[mj].pop_back().unwrap();
        bit.set_val(l + 1, 0);
        bit.set_val(r + 1, 0);
    }
    println!("{}", ans);
}