(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)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
(declaim (inline shuffle!))
(defun shuffle! (vector &optional (start 0) end)
  "Destructively shuffles VECTOR by Fisher-Yates algorithm."
  (declare (vector vector)
           ((mod #.array-total-size-limit) start)
           ((or null (mod #.array-total-size-limit)) end))
  (loop for i from (- (or end (length vector)) 1) above start
        for j = (+ start (random (- (+ i 1) start)))
        do (rotatef (aref vector i) (aref vector j)))
  vector)

(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  "NOTE: cannot read -2^62"
  (declare #.OPT)
  (macrolet ((%read-byte ()
               `(the (unsigned-byte 8)
                     #+swank (char-code (read-char in nil #\Nul))
                     #-swank (sb-impl::ansi-stream-read-byte in nil #.(char-code #\Nul) nil))))
    (let* ((minus nil)
           (result (loop (let ((byte (%read-byte)))
                           (cond ((<= 48 byte 57)
                                  (return (- byte 48)))
                                 ((zerop byte) ; #\Nul
                                  (error "Read EOF or #\Nul."))
                                 ((= byte #.(char-code #\-))
                                  (setq minus t)))))))
      (declare ((integer 0 #.most-positive-fixnum) result))
      (loop
        (let* ((byte (%read-byte)))
          (if (<= 48 byte 57)
              (setq result (+ (- byte 48)
                              (* 10 (the (integer 0 #.(floor most-positive-fixnum 10))
                                         result))))
              (return (if minus (- result) result))))))))

(declaim (inline println-matrix))
(defun println-matrix (array &key (separator #\ ) (key #'identity) (writer #'write) (row-start 0) row-end (col-start 0) col-end)
  "Prints a 2-dimensional array."
  (declare ((array * (* *)) array)
           ((integer 0 #.most-positive-fixnum) row-start col-start))
  (let ((row-end (or row-end (array-dimension array 0)))
        (col-end (or col-end (array-dimension array 1))))
    (declare ((integer 0 #.most-positive-fixnum) row-end col-end))
    (loop for i from row-start below row-end
          do (loop for j from col-start below col-end
                   unless (= j col-start)
                   do (princ separator)
                   do (funcall writer (funcall key (aref array i j))))
             (terpri))))

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

(in-package :cl-user)

(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 test (n seq)
  (let ((mat (make-array (list n n) :element-type 'uint32 :initial-element #xffffffff))
        (plan (make-array (list n n) :element-type 'bit :initial-element 0))
        (res 0))
    (labels ((%get (i j)
               ;; (dbg i j)
               (if (and (<= 0 i (- n 1))
                        (<= 0 j (- n 1)))
                   (aref mat i j)
                   0))
             (decode (p)
               (multiple-value-bind (quot rem) (floor (- p 1) n)
                 (values quot rem))))
      (sb-int:dovector (p (reverse seq))
        (multiple-value-bind (i j) (decode p)
          (setf (aref plan i j) 1))
        (fill (array-storage-vector mat) #xffffffff)
        (dotimes (_ (* n n))
          (dotimes (i n)
            (dotimes (j n)
              (let ((res (min (%get (- i 1) j)
                              (%get (+ i 1) j)
                              (%get i (- j 1))
                              (%get i (+ j 1)))))
                (if (= (aref plan i j) 1)
                    (minf (aref mat i j) (+ res 1))
                    (minf (aref mat i j) res))))))
        (multiple-value-bind (i j) (decode p)
          (setf (aref plan i j) 1)
          (incf res (- (aref mat i j) 1)))
        ;; (println-matrix mat)
        )
      res)))

(defun bench (n sample)
  (loop repeat sample
        do (let ((vec (make-array (* n n) :element-type 'uint31)))
             (dotimes (i (* n n))
               (setf (aref vec i) (+ i 1)))
             (shuffle! vec)
             (assert (= (test n vec) (solve n vec))))))

(defun solve (n ps)
  (declare #.OPT
           (uint16 n)
           ((simple-array uint31 (*)) ps))
  (let* (;; 0-bit: up, 1: down, 2: left, 3: right
         (dists (make-array '(500 500) :element-type 'uint8 :initial-element 0))
         (plan (make-array '(500 500) :element-type 'bit :initial-element 1))
         (que-i (make-array #.(* 500 500) :element-type 'uint16))
         (que-j (make-array #.(* 500 500) :element-type 'uint16))
         (front 0)
         (end 0)
         (res 0))
    (declare (uint16 n)
             (uint32 res front end))
    (dotimes (i (* n n))
      (setf (aref ps i) (- (aref ps i) 1)))
    (dotimes (i n)
      (dotimes (j n)
        (setf (aref dists i j)
              (min (+ i 1) (+ j 1) (- n i) (- n j)))))
    (labels ((enqueue (i j)
               (setf (aref que-i end) i
                     (aref que-j end) j)
               (incf end))
             (dequeue ()
               (multiple-value-prog1
                   (values (aref que-i front) (aref que-j front))
                 (incf front)))
             (queue-reinitialize ()
               (setq front 0 end 0))
             (visit (new-i new-j prev-dist)
               (declare (int32 new-i new-j prev-dist))
               (when (and (<= 0 new-i (- n 1))
                          (<= 0 new-j (- n 1)))
                 (let ((new-dist (+ prev-dist (aref plan new-i new-j))))
                   (when (< new-dist (aref dists new-i new-j))
                     (setf (aref dists new-i new-j) new-dist)
                     (enqueue new-i new-j))))))
      (sb-int:dovector (p ps)
        (queue-reinitialize)
        (multiple-value-bind (i j) (floor p n)
          (decf (aref dists i j))
          (incf res (aref dists i j))
          (setf (aref plan i j) 0)
          (enqueue i j)
          (loop until (= front end)
                do (multiple-value-bind (i j) (dequeue)
                     (let ((dist (aref dists i j)))
                       (visit (- i 1) j dist)
                       (visit (+ i 1) j dist)
                       (visit i (- j 1) dist)
                       (visit i (+ j 1) dist))))))
      res)))

(defun main ()
  (let* ((n (read))
         (ps (make-array (* n n) :element-type 'uint31 :initial-element 0)))
    (dotimes (i (* n n))
      (setf (aref ps i) (read-fixnum)))
    (println (solve n ps))))

#-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 "500~%")
    (let ((vec (make-array (* 500 500))))
      (dotimes (i (* 500 500))
        (setf (aref vec i) (+ i 1)))
      (shuffle! vec)
      (dotimes (i (* 500 500))
        (println (aref vec i) 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 "3
1 3 7 9 5 4 8 6 2
"
    "1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4
6 7 1 4 13 16 10 9 5 11 12 14 15 2 3 8
"
    "3
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "6
11 21 35 22 7 36 27 34 8 20 15 13 16 1 24 3 2 17 26 9 18 32 31 23 19 14 4 25 10 29 28 33 12 6 5 30
"
    "11
")))


Measured memory_bytes: 27292