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.42.0) (judge verdict: Wrong Answer)

use proconio::input;

fn main() {
    input!(s: proconio::marker::Chars);
    let mut mul = vec![0; 26];
    s.iter().for_each(|&c| mul[(c as u8 - b'a') as usize] += 1);
    eprintln!("{:?}", &mul);
    if 1 < mul.iter().copied().filter(|&x| x % 2 == 1).count() {
        println!("-1");
        std::process::exit(0);
    }
    let n = s.len();
    let mut left_count = 0;
    let mut right_count = 0;
    let mut ans = 0;
    let mut left = vec![vec![]; 26];
    let mut right = vec![vec![]; 26];
    let mut center = false;
    for c in s {
        let x = (c as u8 - b'a') as usize;
        if left[x].len() < mul[x] / 2 {
            left[x].push(left_count);
            left_count += 1;
            ans += right_count;
            if center {
                ans += 1;
            }
        } else if mul[x] % 2 == 1 && !center {
            center = true;
            ans += right_count;
        } else {
            right[x].push(n / 2 - 1 - right_count);
            right_count += 1;
        }
    }
    right.iter_mut().for_each(|v| v.reverse());
    println!(
        "{}",
        ans + left
            .iter()
            .zip(right.iter())
            .map(|(v, w)| v
                .iter()
                .zip(w.iter())
                .map(|(i, j)| {
                    eprintln!("(i, j) = {:?}", (i, j));
                    if i < j {
                        j - i
                    } else {
                        0
                    }
                })
                .sum::<usize>())
            .sum::<usize>()
    );
}