Problem:
Score : 800 points

Problem Statement

Mr. Takahashi has in his room an art object with H rows and W columns, made up of H \times W blocks.
Each block has a color represented by a lowercase English letter (a-z).
The color of the block at the i-th row and j-th column is c_{i,j}.

Mr. Takahashi would like to dismantle the object, finding it a bit kitschy for his tastes.
The dismantling is processed by repeating the following operation:

Choose one of the W columns and push down that column one row.
The block at the bottom of that column disappears.

Each time the operation is performed, a cost is incurred.
Since blocks of the same color have a property to draw each other together, the cost of the operation is the number of the pairs of blocks (p, q) such that:

The block p is in the selected column.

The two blocks p and q are horizontally adjacent (before pushing down the column).

The two blocks p and q have the same color.

Mr. Takahashi dismantles the object by repeating the operation H \times W times to get rid of all the blocks.
Compute the minimum total cost to dismantle the object.

Constraints

1 ≤ H ≤ 300

2 ≤ W ≤ 300

All characters c_{i,j} are lowercase English letters (a-z).

Partial Score

In test cases worth 300 points, W = 3.

Input

The input is given from Standard Input in the following format:

H W
c_{1,1}c_{1,2}..c_{1,W}
c_{2,1}c_{2,2}..c_{2,W}
:
c_{H,1}c_{H,2}..c_{H,W}

Output

Print the minimum total cost to dismantle the object.

Sample Input 1

2 3
rrr
brg

Sample Output 1

2

For example, the total cost of 2 can be achieved by performing the operation as follows and this is the minimum value.

Sample Input 2

6 3
xya
xya
ayz
ayz
xaz
xaz

Sample Output 2

0

The total cost of 0 can be achieved by first pushing down all blocks of the middle column, then all of the left column, and all of the right column.

Sample Input 3

4 2
ay
xa
xy
ay

Sample Output 3

0

The total cost of 0 can be achieved by the following operations:

pushing down the right column one row;

pushing down the left column one row;

pushing down all of the right column;

and pushing down all of the left column.

Sample Input 4

5 5
aaaaa
abbba
ababa
abbba
aaaaa

Sample Output 4

24

Sample Input 5

7 10
xxxxxxxxxx
ccccxxffff
cxxcxxfxxx
cxxxxxffff
cxxcxxfxxx
ccccxxfxxx
xxxxxxxxxx

Sample Output 5

130

Solution in Common Lisp (SBCL 1.1.14) (judge verdict: Time Limit Exceeded)

(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
           ;; enclose the form with VALUES to avoid being captured by LOOP macro
           #\# #\> (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)
#-swank (disable-debugger) ; for CS Academy

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

(declaim (inline read-schar))
(defun read-schar (&optional (stream *standard-input*))
  (declare #-swank (sb-kernel:ansi-stream stream)
           (inline read-byte))
  #+swank (read-char stream nil #\Newline) ; on SLIME
  #-swank (code-char (read-byte stream nil #.(char-code #\Newline))))

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

(defun make-costs (h s1 s2)
  (declare (simple-base-string s1 s2))
  (let ((costs1 (make-array (list (+ h 1) (+ h 1))
                            :element-type 'uint32
                            :initial-element 0)))
    (dotimes (init h)
      (loop for delta to (- h init)
            do (loop for i1 from init below (+ init delta)
                     for i2 from 0 below delta
                     do (if (char= (aref s1 i1) (aref s2 i2))
                            (setf (aref costs1 init (+ i2 1))
                                  (+ (aref costs1 init i2) 1))
                            (setf (aref costs1 init (+ i2 1))
                                  (aref costs1 init i2))))))
    costs1))

(defun main ()
  (let* ((h (read))
         (w (read))
         (cs (make-array (list h w) :element-type 'base-char))
         (res 0))
    (dotimes (i h)
      (dotimes (j w (read-schar))
        (setf (aref cs i j) (read-schar))))
    (dotimes (j (- w 1))
      (let ((s1 (make-string h :element-type 'base-char))
            (s2 (make-string h :element-type 'base-char)))
        (dotimes (i h)
          (setf (aref s1 i) (aref cs i j)
                (aref s2 i) (aref cs i (+ j 1))))
        (dbg s1 s2)
        (let ((costs1 (make-costs h s1 s2))
              (costs2 (make-costs h s2 s1))
              (dp (make-array (list (+ h 1) (+ h 1))
                              :element-type 'uint32
                              :initial-element #xffffffff)))
          (dbg costs1 costs2)
          (setf (aref dp 0 0) 0)
          (dotimes (x (+ h 1))
            (dotimes (y (+ h 1))
              (when (< x h)
                (if (>= (+ x 1) y)
                    (minf (aref dp (+ x 1) y)
                          (+ (aref dp x y)
                             (aref costs2 (- (+ x 1) y) y)))
                    (minf (aref dp (+ x 1) y)
                          (+ (aref dp x y)
                             (aref costs1 (- y (+ x 1)) (+ x 1))))))
              (when (< y h)
                (if (>= (+ y 1) x)
                    (minf (aref dp x (+ y 1))
                          (+ (aref dp x y)
                             (aref costs1 (- (+ y 1) x) x)))
                    (minf (aref dp x (+ y 1))
                          (+ (aref dp x y)
                             (aref costs2 (- x (+ y 1)) (+ y 1))))))))
          (incf res (aref dp h h)))))
    (println res)))

#-swank (main)

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

#+swank
(defun io-equal (in-string out-string &key (function #'main) (test #'equal))
  "Passes IN-STRING to *STANDARD-INPUT*, executes FUNCTION, and returns true if
the string output to *STANDARD-OUTPUT* is equal to OUT-STRING."
  (labels ((ensure-last-lf (s)
             (if (eql (uiop:last-char s) #\Linefeed)
                 s
                 (uiop:strcat s uiop:+lf+))))
    (funcall test
             (ensure-last-lf out-string)
             (with-output-to-string (out)
               (let ((*standard-output* out))
                 (with-input-from-string (*standard-input* (ensure-last-lf in-string))
                   (funcall function)))))))

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    (run-program "powershell.exe" '("-Command" "Get-Clipboard") :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* out))
    (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))))))

#+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
   (common-lisp-user::io-equal "2 3
rrr
brg
"
    "2
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "6 3
xya
xya
ayz
ayz
xaz
xaz
"
    "0
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4 2
ay
xa
xy
ay
"
    "0
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "5 5
aaaaa
abbba
ababa
abbba
aaaaa
"
    "24
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "7 10
xxxxxxxxxx
ccccxxffff
cxxcxxfxxx
cxxxxxffff
cxxcxxfxxx
ccccxxfxxx
xxxxxxxxxx
"
    "130
")))