(in-package :cl-user)
(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)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

(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)

(defconstant +mod+ 1000000007)

(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)))

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

;; BEGIN_INSERTED_CONTENTS
(defpackage :cp/modify-macro
  (:use :cl)
  (:export #:minf #:maxf #:mulf #:divf #:iorf #:xorf #:andf))
(in-package :cp/modify-macro)

(macrolet ((def (name fname)
             `(define-modify-macro ,name (new-value) ,fname)))
  (def minf min)
  (def maxf max)
  (def mulf *)
  (def divf /)
  (def iorf logior)
  (def xorf logxor)
  (def andf logand))

;;;
;;; Binary heap
;;;

(defpackage :cp/abstract-heap
  (:use :cl)
  (:export #:heap-empty-error #:define-binary-heap))
(in-package :cp/abstract-heap)

(define-condition heap-empty-error (error)
  ((heap :initarg :heap :reader heap-empty-error-heap))
  (:report
   (lambda (condition stream)
     (format stream "Attempted to pop empty heap ~W" (heap-empty-error-heap condition)))))

(defmacro define-binary-heap (name &key (order '#'>) (element-type 'fixnum))
  "Defines a binary heap specialized for the given order and the element
type. This macro defines a structure of the given NAME and relevant functions:
MAKE-<NAME>, <NAME>-PUSH, <NAME>-POP, <NAME>-REINITIALIZE, <NAME>-EMPTY-P,
<NAME>-COUNT, and <NAME>-PEEK."
  (check-type name symbol)
  (let* ((string-name (string name))
         (fname-push (intern (format nil "~A-PUSH" string-name)))
         (fname-pop (intern (format nil "~A-POP" string-name)))
         (fname-reinitialize (intern (format nil "~A-REINITIALIZE" string-name)))
         (fname-empty-p (intern (format nil "~A-EMPTY-P" string-name)))
         (fname-count (intern (format nil "~A-COUNT" string-name)))
         (fname-peek (intern (format nil "~A-PEEK" string-name)))
         (fname-make (intern (format nil "MAKE-~A" string-name)))
         (acc-position (intern (format nil "~A-POSITION" string-name)))
         (acc-data (intern (format nil "~A-DATA" string-name))))
    `(progn
       (locally
           ;; prevent style warnings
           (declare #+sbcl (sb-ext:muffle-conditions style-warning))
         (defstruct (,name
                     (:constructor ,fname-make
                         (size
                          &aux
                          (data (make-array (1+ size)
                                            :element-type ',(if (eql element-type '*) t  element-type))))))
           (data nil :type (simple-array ,element-type (*)))
           (position 1 :type (integer 1 #.array-total-size-limit))))

       (declaim #+sbcl (sb-ext:maybe-inline ,fname-push))
       (defun ,fname-push (obj heap)
         "Adds OBJ to HEAP."
         (declare (optimize (speed 3))
                  (type ,name heap))
         (symbol-macrolet ((position (,acc-position heap)))
           (when (>= position (length (,acc-data heap)))
             (setf (,acc-data heap)
                   (adjust-array (,acc-data heap)
                                 (min (- array-total-size-limit 1)
                                      (* position 2)))))
           (let ((data (,acc-data heap)))
             (declare ((simple-array ,element-type (*)) data))
             (labels ((heapify (pos)
                        (declare (optimize (speed 3) (safety 0)))
                        (unless (= pos 1)
                          (let ((parent-pos (ash pos -1)))
                            (when (funcall ,order (aref data pos) (aref data parent-pos))
                              (rotatef (aref data pos) (aref data parent-pos))
                              (heapify parent-pos))))))
               (setf (aref data position) obj)
               (heapify position)
               (incf position)
               heap))))

       (declaim #+sbcl (sb-ext:maybe-inline ,fname-pop))
       (defun ,fname-pop (heap)
         "Removes and returns the element at the top of HEAP."
         (declare (optimize (speed 3))
                  (type ,name heap))
         (symbol-macrolet ((position (,acc-position heap)))
           (let ((data (,acc-data heap)))
             (declare ((simple-array ,element-type (*)) data))
             (labels ((heapify (pos)
                        (declare (optimize (speed 3) (safety 0))
                                 ((integer 1 #.array-total-size-limit) pos))
                        (let* ((child-pos1 (+ pos pos))
                               (child-pos2 (1+ child-pos1)))
                          (when (<= child-pos1 position)
                            (if (<= child-pos2 position)
                                (if (funcall ,order (aref data child-pos1) (aref data child-pos2))
                                    (unless (funcall ,order (aref data pos) (aref data child-pos1))
                                      (rotatef (aref data pos) (aref data child-pos1))
                                      (heapify child-pos1))
                                    (unless (funcall ,order (aref data pos) (aref data child-pos2))
                                      (rotatef (aref data pos) (aref data child-pos2))
                                      (heapify child-pos2)))
                                (unless (funcall ,order (aref data pos) (aref data child-pos1))
                                  (rotatef (aref data pos) (aref data child-pos1))))))))
               (when (= position 1)
                 (error 'heap-empty-error :heap heap))
               (prog1 (aref data 1)
                 (decf position)
                 (setf (aref data 1) (aref data position))
                 (heapify 1))))))

       (declaim (inline ,fname-reinitialize))
       (defun ,fname-reinitialize (heap)
         "Makes HEAP empty."
         (setf (,acc-position heap) 1)
         heap)

       (declaim (inline ,fname-empty-p))
       (defun ,fname-empty-p (heap)
         "Returns true iff HEAP is empty."
         (= 1 (,acc-position heap)))

       (declaim (inline ,fname-count))
       (defun ,fname-count (heap)
         "Returns the current number of the elements in HEAP."
         (- (,acc-position heap) 1))

       (declaim (inline ,fname-peek))
       (defun ,fname-peek (heap)
         "Returns the topmost element of HEAP."
         (if (= 1 (,acc-position heap))
             (error 'heap-empty-error :heap heap)
             (aref (,acc-data heap) 1))))))

#|

;|#

;; BEGIN_USE_PACKAGE
(eval-when (:compile-toplevel :load-toplevel :execute)
  (use-package :cp/abstract-heap :cl-user))
(eval-when (:compile-toplevel :load-toplevel :execute)
  (use-package :cp/modify-macro :cl-user))
(in-package :cl-user)

;;;
;;; Body
;;;

;; cost string sign
(define-binary-heap heap
  :order (lambda (x y)
           (< (the fixnum (car x)) (the fixnum (car y))))
  :element-type list)

(declaim (inline palindrome-p))
(defun palindrome-p (s)
  (let ((n (length s)))
    (loop for i from 0 below (floor n 2)
          always (char= (aref s i) (aref s (- n i 1))))))
(defun main ()
  (let* ((n (read))
         (ss (make-array n :element-type 'simple-base-string))
         (ss-rev (make-array n :element-type 'simple-base-string))
         (cs (make-array n :element-type 'uint31 :initial-element 0))
         (res most-positive-fixnum))
    (declare (uint62 res))
    (dotimes (i n)
      (let* ((line (read-line))
             (pos (position #\  line))
             (s (subseq line 0 pos))
             (c (read-from-string line t nil :start pos)))
        (setf (aref ss i) (coerce s 'simple-base-string)
              (aref ss-rev i) (reverse (aref ss i))
              (aref cs i) c)))
    (labels ((dfs (rest sign score depth)
               (declare (simple-base-string rest)
                        (uint62 score depth)
                        (int32 sign))
               (dbg rest sign score depth)
               (when (palindrome-p rest)
                 (minf res score)
                 (return-from dfs))
               (when (and (< score res) (< depth 120))
                 (cond ((= sign 1)
                        (dotimes (i n)
                          (let* ((s (aref ss-rev i))
                                 (c (aref cs i))
                                 (pos (or (mismatch rest s) (length s))))
                            (declare (simple-base-string s))
                            (when (= (min (length rest) (length s)) pos)
                              (if (<= (length rest) (length s))
                                  (dfs (subseq s pos (length s)) -1 (+ score c) (+ depth 1))
                                  (dfs (subseq rest pos (length rest)) 1 (+ score c) (+ depth 1)))))))
                       ((= sign -1)
                        (dotimes (i n)
                          (let* ((s (aref ss i))
                                 (c (aref cs i))
                                 (pos (or (mismatch rest s) (length s))))
                            (declare (simple-base-string s))
                            (when (= (min (length rest) (length s)) pos)
                              (if (<= (length rest) (length s))
                                  (dfs (subseq s pos (length s)) 1 (+ score c) (+ depth 1))
                                  (dfs (subseq rest pos (length rest)) -1 (+ score c) (+ depth 1)))))))
                       (t (error "Huh?"))))))
      (dotimes (i n)
        (dfs (aref ss i) 1 (aref cs i) 0))
      (println (if (= res most-positive-fixnum)
                   -1
                   res)))))

#-swank (main)

;;;
;;; Test and benchmark
;;;

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    #+os-windows (run-program "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)
    #+os-unix (run-program "xsel" '("-b" "-o") :output out :search t)))

#+swank (defparameter *this-pathname* (uiop:current-lisp-file-pathname))
#+swank (defparameter *dat-pathname* (uiop:merge-pathnames* "test.dat" *this-pathname*))

#+swank
(defun run (&optional thing (out *standard-output*))
  "THING := null | string | symbol | pathname

null: run #'MAIN using the text on clipboard as input.
string: run #'MAIN using the string as input.
symbol: alias of FIVEAM:RUN!.
pathname: run #'MAIN using the text file as input."
  (let* ((*standard-output* (or out (make-string-output-stream)))
         (res (etypecase thing
                (null
                 (with-input-from-string (*standard-input* (delete #\Return (get-clipbrd)))
                   (main)))
                (string
                 (with-input-from-string (*standard-input* (delete #\Return thing))
                   (main)))
                (symbol (5am:run! thing))
                (pathname
                 (with-open-file (*standard-input* thing)
                   (main))))))
    (if out res (get-output-stream-string *standard-output*))))

#+swank
(defun gen-dat ()
  (uiop:with-output-file (out *dat-pathname* :if-exists :supersede)
    (format out "")))

#+swank
(defun bench (&optional (out (make-broadcast-stream)))
  (time (run *dat-pathname* out)))

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (equal "7
"
          (run "3
ba 3
abc 4
cbaa 5
" nil)))
  (it.bese.fiveam:is
   (equal "11
"
          (run "2
abcab 5
cba 3
" nil)))
  (it.bese.fiveam:is
   (equal "8
"
          (run "4
ab 5
cba 3
a 12
ab 10
" nil)))
  (it.bese.fiveam:is
   (equal "-1
"
          (run "2
abc 1
ab 2
" nil))))


Measured memory_bytes: 26424