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)

fn inversion(b: &mut [usize]) -> u64 {
    let n = b.len();
    if n <= 1 {
        return 0;
    }
    let m = n / 2;
    let mut ans = inversion(&mut b[..m]) + inversion(&mut b[m..]);
    let mut c = vec![];
    let mut i = 0;
    let mut j = m;
    while i < m && j < n {
        if b[i] <= b[j] {
            c.push(b[i]);
            i += 1;
        } else {
            ans += (m - i) as u64;
            c.push(b[j]);
            j += 1;
        }
    }
    while i < m {
        c.push(b[i]);
        i += 1;
    }
    for (i, c) in c.iter().enumerate() {
        b[i] = *c;
    }
    ans
}

fn run() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let s: Vec<usize> = s.trim().chars().map(|c| c as usize - 'a' as usize).collect();
    let f = 26;
    let mut a = vec![vec![]; f];
    for (i, &k) in s.iter().enumerate() {
        a[k].push(i);
    }
    let mut odd = 0;
    for i in 0..f {
        odd += a[i].len() & 1;
    }
    if odd > 1 {
        println!("-1");
        return;
    }
    let mut ans = 0u64;
    let mut p = vec![0; f];
    let mut b = vec![];
    let mut back = 0;
    for (_, &k) in s.iter().enumerate() {
        p[k] += 1;
        if 2 * p[k] - 1 == a[k].len() {
            ans += back;
            back += 1;
        } else if 2 * p[k] <= a[k].len() {
            ans += back
        } else {
            b.push(a[k][a[k].len() - p[k]]);
            back += 1;
        }
    }
    b.reverse();
    ans += inversion(&mut b);
    println!("{}", ans);
}

fn main() {
    run();
}