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)

// https://atcoder.jp/contests/arc088/tasks/arc088_c
//
#![allow(unused_imports)]
use std::io::*;
use std::io::Write;
use std::fmt::*;
use std::str::*;
use std::cmp::*;
use std::collections::*;

// Input macros.
// Original by tanakh: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        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)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };

    ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

#[allow(unused_macros)]
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, [ next / $t:tt ]) => {
        {
            let len = read_value!($iter, usize);
            (0..len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
        }
    };

    ($iter:expr, switch) => {
        {
            let ty = read_value!($iter, i32);
            if ty == 1 {
                vec![ty, read_value!($iter, i32), read_value!($iter, i32)]
            } else if ty == 2 {
                vec![ty, read_value!($iter, i32)]
            } else {
                vec![ty, read_value!($iter, i32)]
            }
        }
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_macros)]
macro_rules! read_line {
    ($t:tt) => {
        {
            let mut s = String::new();
            std::io::stdin().read_line(&mut s).unwrap();
            s.trim_right().parse::<$t>().unwrap()
        }
    }
}

#[allow(unused_macros)]
macro_rules! dvec {
    ($t:expr ; $len:expr) => {
        vec![$t; $len]
    };

    ($t:expr ; $len:expr, $($rest:expr),*) => {
        vec![dvec!($t; $($rest),*); $len]
    };
}

#[allow(unused_macros)]
macro_rules! ifv {
    ($t:expr, $a:expr, $b: expr) => {
        if $t { $a } else { $b }
    }
}

#[allow(unused_macros)]
macro_rules! fill {
    ($t:expr, $v:expr) => {
        for i in 0..$t.len() {
            $t[i] = $v;
        }
    };
}

#[allow(unused_macros)]
macro_rules! join {
    ($t:expr, $glue:expr) => {
        $t.into_iter().map(|w| w.to_string()).collect::<Vec<_>>().join($glue)
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

// ===


fn ctou(c: char) -> usize {
    (c as u8 - b'a') as usize
}

fn solve_even(a: Vec<i32>) -> i64 {
    let n = a.len();
    let mut limit = 0;
    for i in 0..n {
        if a[i] == -1 {
            limit = i;
        }
    }
    let mut sum = 0;
    let mut cnt = 0;
    for i in (0..limit).rev() {
        if a[i] == 1 {
            sum += (limit - i) as i64;
            sum -= cnt;
            cnt += 1;
        }
    }
    sum
}

fn solve_odd(a: Vec<i32>, opos: usize) -> i64 {
    let n = a.len();
    let mut sum = 0;
    let mut lcnt = 0;
    let mut rcnt = 0;
    for i in (0..opos).rev() {
        if a[i] == 1 {
            sum += (opos - i) as i64;
            sum -= lcnt;
            lcnt += 1;
        }
    }
    for i in opos+1..n {
        if a[i] == -1 {
            sum += (i - opos) as i64;
            sum -= rcnt;
            rcnt += 1;
        }
    }
    sum + lcnt * rcnt
}

// ===

struct FenwickTree<T> {
    data: Vec<T>
}

impl<T: Copy + Default + std::ops::Add + std::ops::AddAssign + std::ops::Sub> FenwickTree<T> {
    fn new(n: usize, initial: T) -> Self {
        FenwickTree { data: vec![initial; n+1] }
    }

    /// Computes sum value of ([0, i)).
    fn sum(&self, i: usize) -> T {
        let mut idx = i as i64;
        let mut ret = T::default();
        while idx > 0 {
            ret += self.data[idx as usize];
            idx -= idx & (-idx);
        }
        ret
    }

    /// Adds value x into i-th position.
    fn add(&mut self, i: usize, x: T) {
        let mut idx = (i + 1) as i64;
        while idx < self.data.len() as i64 {
            self.data[idx as usize] += x;
            idx += idx & (-idx);
        }
    }

    fn range(&self, r: std::ops::Range<usize>) -> <T as std::ops::Sub>::Output {
        self.sum(r.end) - self.sum(r.start)
    }
}
// ===

fn b2(a: Vec<usize>) -> i64 {
    // debug!(a);
    if a.len() <= 1 {
        return 0;
    }
    let n = a.len();
    let mut total = 0;
    let mut bit = FenwickTree::new(n+10, 0i64);
    for i in 0..n {
        total += bit.range(a[i]+1..n);
        bit.add(a[i], 1);
    }
    total
}

fn solve(s: Vec<char>) -> i64 {
    let n = s.len();

    let mut pos = vec![vec![]; 26];
    for i in 0..n {
        let c = ctou(s[i]);
        pos[c].push(i);
    }
    let mut odds = vec![];
    for i in 0..26 {
        if pos[i].len() % 2 == 1 {
            odds.push(i);
        }
    }
    if odds.len() != n % 2 {
        return -1;
    }

    let mut a = vec![0; n];
    let mut pairs = vec![];
    for i in 0..26 {
        let cn = pos[i].len();
        let half = cn/2;
        for j in 0..half {
            a[pos[i][j]] = -1;
            a[pos[i][cn-1-j]] = 1;
            pairs.push((pos[i][j], pos[i][cn-1-j]));
        }
    }

    pairs.sort();
    pairs.reverse();

    let mut right_half = pairs.into_iter().zip(0..n).map(|(x, idx)| (x.1, idx)).collect::<Vec<_>>();
    right_half.sort();
    let mut map = vec![0; n/2];
    for i in 0..n/2 {
        map[i] = right_half[i].1;
    }


    let cost = b2(map);
    let eocost = if odds.len() == 0 {
        solve_even(a)
    } else {
        let on = pos[odds[0]].len();
        solve_odd(a, pos[odds[0]][on/2])
    };
    // debug!(cost, eocost);
    cost + eocost
}

fn main() {
    input! {
        s: chars
    };
    println!("{}", solve(s));
}