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 Common Lisp (SBCL 1.1.14) (judge verdict: Wrong Answer)

;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) (read s nil nil t))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
;;;
;;; ARRAY-ELEMENT-TYPE is not constant-folded on SBCL version earlier than
;;; 1.5.0. See
;;; https://github.com/sbcl/sbcl/commit/9f0d12e7ab961828931d01c0b2a76a5885ad35d2
;;;

(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-c:deftransform array-element-type ((array))
    (let ((type (sb-c::lvar-type array)))
      (flet ((element-type (type)
               (and (sb-c::array-type-p type)
                    (sb-int:neq (sb-kernel::array-type-specialized-element-type type) sb-kernel:*wild-type*)
                    (sb-kernel:type-specifier (sb-kernel::array-type-specialized-element-type type)))))
        (cond ((let ((type (element-type type)))
                 (and type
                      `',type)))
              ((sb-kernel:union-type-p type)
               (let (result)
                 (loop for type in (sb-kernel:union-type-types type)
                       for et = (element-type type)
                       unless (and et
                                   (if result
                                       (equal result et)
                                       (setf result et)))
                       do (sb-c::give-up-ir1-transform))
                 `',result))
              ((sb-kernel:intersection-type-p type)
               (loop for type in (sb-kernel:intersection-type-types type)
                     for et = (element-type type)
                     when et
                     return `',et
                     finally (sb-c::give-up-ir1-transform)))
              (t
               (sb-c::give-up-ir1-transform)))))))

;;;
;;; Compute inversion number by merge sort
;;;

(declaim (inline %merge-count))
(defun %merge-count (l mid r source-vec dest-vec predicate)
  (declare ((integer 0 #.array-total-size-limit) l mid r)
           (function predicate))
  (loop with count of-type (integer 0 #.most-positive-fixnum) = 0
        with i = l
        with j = mid
        for idx from l
        when (= i mid)
        do (loop for j from j below r
                 for idx from idx
                 do (setf (aref dest-vec idx)
                          (aref source-vec j))
                 finally (return-from %merge-count count))
        when (= j r)
        do (loop for i from i below mid
                 for idx from idx
                 do (setf (aref dest-vec idx)
                          (aref source-vec i))
                 finally (return-from %merge-count count))
        do (if (funcall predicate
                        (aref source-vec j)
                        (aref source-vec i))
               (setf (aref dest-vec idx) (aref source-vec j)
                     j (1+ j)
                     count (+ count (- mid i)))
               (setf (aref dest-vec idx) (aref source-vec i)
                     i (1+ i)))))

(defmacro with-fixnum+ (form)
  (let ((fixnum+ '(integer 0 #.most-positive-fixnum)))
    `(the ,fixnum+
          ,(reduce (lambda (f1 f2)`(,(car form)
                                   (the ,fixnum+ ,f1)
                                   (the ,fixnum+ ,f2)))
	           (cdr form)))))

(declaim (inline %calc-by-insertion-sort!))
(defun %calc-by-insertion-sort! (vec predicate l r)
  (declare (function predicate)
           ((integer 0 #.array-total-size-limit) l r))
  (loop with inv-count of-type (integer 0 #.most-positive-fixnum) = 0
        for end from (+ l 1) below r
        do (loop for i from end above l
                 while (funcall predicate (aref vec i) (aref vec (- i 1)))
                 do (rotatef (aref vec (- i 1)) (aref vec i))
                    (incf inv-count))
        finally (return inv-count)))

;; NOTE: This function is slow on SBCL version earlier than 1.5.0 as
;; constant-folding of ARRAY-ELEMENT-TYPE doesn't work. Use
;; array-element-type.lisp if necessary.
(declaim (inline count-inversions!))
(defun count-inversions! (vector predicate &key (start 0) end)
  "Calculates the number of the inversions of VECTOR w.r.t. the strict order
PREDICATE. This function sorts VECTOR as a side effect."
  (declare (vector vector)
           (function predicate))
  (let ((end (or end (length vector))))
    (declare ((integer 0 #.array-total-size-limit) start end))
    (assert (<= start end))
    (let ((buffer (make-array end :element-type (array-element-type vector))))
      (labels
          ((recur (l r merge-to-vec1-p)
             (declare (optimize (safety 0))
                      ((integer 0 #.array-total-size-limit) l r))
             (cond ((= l r) 0)
                   ((= (+ l 1) r)
                    (unless merge-to-vec1-p
                      (setf (aref buffer l) (aref vector l)))
                    0)
                   ;; It is faster to use insertion sort. I don't adopt it
                   ;; by default, however, because that makes it hard to
                   ;; change the code to fit some special settings.
                   ;; ((and (<= (- r l) 24) merge-to-vec1-p)
                   ;;  (%calc-by-insertion-sort! vector predicate l r))
                   (t
                    (let ((mid (floor (+ l r) 2)))
                      (with-fixnum+
                          (+ (recur l mid (not merge-to-vec1-p))
                             (recur mid r (not merge-to-vec1-p))
                             (if merge-to-vec1-p
                                 (%merge-count l mid r buffer vector predicate)
                                 (%merge-count l mid r vector buffer predicate)))))))))
        (recur start end t)))))

(defmacro dbg (&rest forms)
  #+swank
  (if (= (length forms) 1)
      `(format *error-output* "~A => ~A~%" ',(car forms) ,(car forms))
      `(format *error-output* "~A => ~A~%" ',forms `(,,@forms)))
  #-swank (declare (ignore forms)))

(defmacro define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~A" b)) () '(unsigned-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~A" b)) () '(signed-byte ,b))) bits)))
(define-int-types 2 4 7 8 15 16 31 32 62 63 64)

(declaim (inline println))
(defun println (obj &optional (stream *standard-output*))
  (let ((*read-default-float-format* 'double-float))
    (prog1 (princ obj stream) (terpri stream))))

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(declaim (inline to-code))
(defun to-code (c)
  (- (char-code c) #.(char-code #\a)))

(declaim (inline make-histogram))
(defun make-histogram (s)
  (let ((res (make-array 26 :element-type 'uint32 :initial-element 0)))
    (sb-int:dovector (c s res)
      (incf (aref res (to-code c))))))

(defun solve-even (s)
  (declare (simple-base-string s))
  (let* ((len (length s))
         (len/2 (floor len 2))
         (histo (make-histogram s))
         (histo1 (make-array 26 :element-type 'uint32 :initial-element 0))
         (histo2 (make-array 26 :element-type 'uint32 :initial-element 0))
         (in-left (make-array len :fill-pointer 0))
         (to-right (make-array len :fill-pointer 0))
         (in-right (make-array len :fill-pointer 0))
         (to-left (make-array len :fill-pointer 0))
         (difference 0)
         (res 0))
    (declare (uint62 difference res))
    (assert (evenp len))
    (dotimes (i len/2 (fill histo1 0))
      (let* ((c (aref s i))
             (code (to-code c)))
        (incf (aref histo1 code))
        (when (> (aref histo1 code) (floor (aref histo code) 2))
          (incf difference))))
    (let ((delta difference))
      (declare (uint62 delta))
      (dotimes (i len/2)
        (let* ((c (aref s i))
               (code (to-code c)))
          (incf (aref histo1 code))
          (if (> (aref histo1 code) (floor (aref histo code) 2))
              (progn
                (vector-push (cons c i) to-right)
                (incf res (- (- len/2 delta) i))
                (decf delta))
              (vector-push (cons c i) in-left)))))
    (let ((delta difference))
      (declare (uint62 delta))
      (loop for i from (- len 1) downto len/2
            do (let* ((c (aref s i))
                      (code (to-code c)))
                 (incf (aref histo2 code))
                 (if (> (aref histo2 code) (floor (aref histo code) 2))
                     (progn
                       (vector-push (cons c i) to-left)
                       (incf res (- i (+ len/2 delta -1)))
                       (decf delta))
                     (vector-push (cons c i) in-right)))
            finally (setq to-left (nreverse to-left)
                          in-right (nreverse in-right))))
    (assert (= (length to-right) (length to-left)))
    (incf res (expt (length to-right) 2))
    (let ((tmp-left (map 'simple-base-string #'car (concatenate 'simple-vector in-left to-left)))
          (tmp-right (map 'simple-base-string #'car (concatenate 'simple-vector to-right in-right)))
          (ords (make-array 26 :element-type 'list :initial-element nil)))
      (loop for i from (- len/2 1) downto 0
            for ord from 0 below len/2
            do (push ord (aref ords (to-code (aref tmp-left i)))))
      (dotimes (i 26)
        (setf (aref ords i) (nreverse (aref ords i))))
      (let ((ord-right (map '(simple-array uint32 (*))
                            (lambda (c)
                              (pop (aref ords (to-code c))))
                            tmp-right)))
        (incf res (count-inversions! ord-right #'<)))
      res)))

(defun main ()
  (let* ((s (coerce (read-line) 'simple-base-string))
         (len (length s))
         (len/2 (floor len 2))
         (histo (make-histogram s)))
    (println
     (if (evenp len)
         (if (every #'evenp histo)
             (solve-even s)
             -1)
         (let ((odd-chars (loop for i below 26
                                for x across histo
                                when (oddp x)
                                collect (code-char (+ 97 i)))))
           (if (= (length odd-chars) 1)
               (let* ((odd-char (car odd-chars))
                      (pos0 (or (position odd-char s :end len/2 :from-end t)
                                most-negative-fixnum))
                      (pos1 (or (position odd-char s :start len/2)
                                most-positive-fixnum))
                      (pos (if (<= (- len/2 pos0) (- pos1 len/2))
                               pos0
                               pos1))
                      (s (concatenate 'simple-base-string
                                      (subseq s 0 pos)
                                      (subseq s (+ pos 1))))
                      (res (min (- len/2 pos0) (- pos1 len/2))))
                 (+ res (solve-even s)))
               -1))))))

#-swank (main)