Problem:
Score : 1100 points

Problem Statement

We have a grid with N rows and M columns of squares.
Each integer from 1 to NM is written in this grid once.
The number written in the square at the i-th row from the top and the j-th column from the left is A_{ij}.

You need to rearrange these numbers as follows:

First, for each of the N rows, rearrange the numbers written in it as you like.

Second, for each of the M columns, rearrange the numbers written in it as you like.

Finally, for each of the N rows, rearrange the numbers written in it as you like.

After rearranging the numbers, you want the number written in the square at the i-th row from the top and the j-th column from the left to be M\times (i-1)+j.
Construct one such way to rearrange the numbers. The constraints guarantee that it is always possible to achieve the objective.

Constraints

1 \leq N,M \leq 100

1 \leq A_{ij} \leq NM

A_{ij} are distinct.

Input

Input is given from Standard Input in the following format:

N M
A_{11} A_{12} ... A_{1M}
:
A_{N1} A_{N2} ... A_{NM}

Output

Print one way to rearrange the numbers in the following format:

B_{11} B_{12} ... B_{1M}
:
B_{N1} B_{N2} ... B_{NM}
C_{11} C_{12} ... C_{1M}
:
C_{N1} C_{N2} ... C_{NM}

Here B_{ij} is the number written in the square at the i-th row from the top and the j-th column from the left after Step 1, and C_{ij} is the number written in that square after Step 2.

Sample Input 1

3 2
2 6
4 3
1 5

Sample Output 1

2 6
4 3
5 1
2 1
4 3
5 6

Sample Input 2

3 4
1 4 7 10
2 5 8 11
3 6 9 12

Sample Output 2

1 4 7 10
5 8 11 2
9 12 3 6
1 4 3 2
5 8 7 6
9 12 11 10

Solution in Common Lisp (SBCL 2.0.3) (judge verdict: Runtime Error)

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

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

;;;
;;; Maximum bipartite matching (Hopcroft-Karp, O(E sqrt(V)))
;;;

;; NOTE: The number of elements in the graph must be less than 2^32-1 as we use
;; (UNSIGNED-BYTE 32) here for efficiency.

;; NOTE: Pay attention to the stack size!

(defconstant +graph-inf-distance+ #xffffffff)

(defstruct (bipartite-graph
            (:constructor make-bgraph
                (size1
                 size2
                 &aux
                 (graph1 (make-array size1 :element-type 'list :initial-element nil))
                 (matching1 (make-array size1 :element-type 'fixnum :initial-element -1))
                 (matching2 (make-array size2 :element-type 'fixnum :initial-element -1))))
            (:conc-name bgraph-))
  (size1 0 :type (unsigned-byte 32))
  (size2 0 :type (unsigned-byte 32))
  (graph1 nil :type (simple-array list (*)))
  (matching1 nil :type (simple-array fixnum (*)))
  (matching2 nil :type (simple-array fixnum (*))))

(declaim (inline bgraph-add-edge!))
(defun bgraph-add-edge! (bgraph vertex1 vertex2)
  (push vertex2 (aref (bgraph-graph1 bgraph) vertex1))
  bgraph)

(defun %fill-levels (bgraph levels1 levels2 queue)
  "Does BFS and fills LEVELS."
  (declare (optimize (speed 3) (safety 0))
           ((simple-array (unsigned-byte 32) (*)) levels1 levels2 queue))
  (let ((graph1 (bgraph-graph1 bgraph))
        (matching1 (bgraph-matching1 bgraph))
        (matching2 (bgraph-matching2 bgraph))
        (q-front 0)
        (q-end 0)
        (found nil))
    (declare ((integer 0 #.most-positive-fixnum) q-front q-end))
    (labels ((enqueue (obj)
               (setf (aref queue q-end) obj)
               (incf q-end))
             (dequeue ()
               (prog1 (aref queue q-front)
                 (incf q-front))))
      (declare (inline enqueue dequeue))
      (fill levels1 +graph-inf-distance+)
      (fill levels2 +graph-inf-distance+)
      (dotimes (i (bgraph-size1 bgraph))
        (when (= -1 (aref matching1 i))
          (setf (aref levels1 i) 0)
          (enqueue i)))
      (loop until (= q-front q-end)
            for vertex = (dequeue)
            do (dolist (next (aref graph1 vertex))
                 (when (= +graph-inf-distance+ (aref levels2 next))
                   (setf (aref levels2 next) (+ 1 (aref levels1 vertex)))
                   (let ((partner (aref matching2 next)))
                     (when (= -1 partner)
                       (setq found t)
                       (return))
                     (setf (aref levels1 partner) (+ 1 (aref levels2 next)))
                     (enqueue partner))))))
    found))

(defun %find-matching (bgraph src levels1 levels2)
  "Does DFS and makes matching greedily on the residual network."
  (declare (optimize (speed 3) (safety 0))
           ((integer 0 #.most-positive-fixnum) src)
           ((simple-array (unsigned-byte 32) (*)) levels1 levels2))
  (let ((matching1 (bgraph-matching1 bgraph))
        (matching2 (bgraph-matching2 bgraph))
        (graph1 (bgraph-graph1 bgraph)))
    (labels ((dfs (v)
               (declare ((integer 0 #.most-positive-fixnum) v))
               (dolist (next (aref graph1 v))
                 (when (= (aref levels2 next) (+ 1 (aref levels1 v)))
                   (setf (aref levels2 next) +graph-inf-distance+) ; mark visited
                   (let ((partner (aref matching2 next)))
                     (when (or (= -1 partner) (dfs partner))
                       (setf (aref matching1 v) next
                             (aref matching2 next) v
                             (aref levels1 v) +graph-inf-distance+ ; mark visited
                             )
                       (return-from dfs t)))))
               (setf (aref levels1 v) +graph-inf-distance+) ; mark visited
               nil ; not matched
               ))
      (dfs src))))

(declaim (ftype (function * (values (unsigned-byte 32) &optional)) bgraph-build-matching!))
(defun bgraph-build-matching! (bgraph)
  "Makes a maximum bipartite matching and returns two vectors: correspondence
from group 1 to group 2, and correspondence from group 2 to group 1. At an
unmatched vertex, -1 is stored."
  (declare (optimize (speed 3)))
  (let* ((size1 (bgraph-size1 bgraph))
         (size2 (bgraph-size2 bgraph))
         (matching1 (bgraph-matching1 bgraph))
         (levels1 (make-array size1 :element-type '(unsigned-byte 32)))
         (levels2 (make-array size2 :element-type '(unsigned-byte 32)))
         (queue (make-array (+ size1 size2) :element-type '(unsigned-byte 32)))
         (count 0))
    (declare ((integer 0 #.most-positive-fixnum) count))
    (loop while (%fill-levels bgraph levels1 levels2 queue)
          do (dotimes (v size1)
               (when (and (= -1 (aref matching1 v))
                          (%find-matching bgraph v levels1 levels2))
                 (incf count))))
    count))

;; not tested
(defun coerce-to-bgraph (graph)
  "Converts adjacency lists representation of undirected graph to
BIPARTITE-GRAPH.

GRAPH := vector of adjacency lists"
  (declare (vector graph))
  (let* ((n (length graph))
         (visited (make-array n :element-type 'bit :initial-element 0))
         (colors (make-array n :element-type 'bit :initial-element 0))
         (nums (make-array n :element-type 'fixnum))
         (size0 0)
         (size1 0))
    (declare ((integer 0 #.most-positive-fixnum) size0 size1))
    (labels ((dfs (vertex color)
               (cond ((zerop (aref visited vertex))
                      (setf (aref visited vertex) 1
                            (aref colors vertex) color)
                      (if (zerop color)
                          (setf (aref nums vertex) size0
                                size0 (+ size0 1))
                          (setf (aref nums vertex) size1
                                size1 (+ size1 1)))
                      (if (= color 1)
                          (dolist (neighbor (aref graph vertex))
                            (dfs neighbor 0))
                          (dolist (neighbor (aref graph vertex))
                            (dfs neighbor 1))))
                     ((/= color (aref colors vertex))
                      (error "Not bipartite.")))))
      (dotimes (i n)
        (when (zerop (aref visited i))
          (dfs i 1)))
      (let ((bgraph (make-bgraph size0 size1)))
        (dotimes (i n)
          (when (zerop (aref colors i))
            (let ((i-num (aref nums i)))
              (dolist (j (aref graph i))
                (let ((j-num (aref nums j)))
                  (bgraph-add-edge! bgraph i-num j-num))))))
        bgraph))))

;; not tested
(declaim (ftype (function * (values (simple-array (integer 0 #.most-positive-fixnum) (*))
                                    (simple-array (integer 0 #.most-positive-fixnum) (*))
                                    &optional))
                bgraph-decompose!))
(defun bgraph-decompose (bgraph)
  "Decomposes a residual network to strongly connected components by Tarjan's
algorithm. BGRAPH-BUILD-MATCHING! must be called beforehand."
  (declare (optimize (speed 3)))
  (let* ((size1 (bgraph-size1 bgraph))
         (size2 (bgraph-size2 bgraph))
         (total-size (+ size1 size2 2))
         (source (+ size1 size2))
         (sink (+ size1 size2 1))
         (graph1 (bgraph-graph1 bgraph))
         (matching1 (bgraph-matching1 bgraph))
         (matching2 (bgraph-matching2 bgraph))
         (ord 0) ; in-order
         (ords (make-array total-size :element-type 'fixnum :initial-element -1))
         (lowlinks (make-array total-size :element-type 'fixnum))
         (components (make-array total-size
                                 :element-type '(integer 0 #.most-positive-fixnum)))
         (comp-index 0) ; index number of component
         (sizes (make-array total-size
                            :element-type '(integer 0 #.most-positive-fixnum)
                            :initial-element 0))
         (stack (make-array total-size :element-type '(integer 0 #.most-positive-fixnum)))
         (end 0) ; stack pointer
         (in-stack (make-array total-size :element-type 'bit :initial-element 0)))
    (declare ((integer 0 #.most-positive-fixnum) ord end comp-index source sink total-size))
    (labels ((%push (v)
               (setf (aref stack end) v
                     (aref in-stack v) 1)
               (incf end))
             (%pop ()
               (decf end)
               (let ((v (aref stack end)))
                 (setf (aref in-stack v) 0)
                 v))
             (frob (v next)
               (cond ((= -1 (aref ords next))
                      (visit next)
                      (setf (aref lowlinks v)
                            (min (aref lowlinks v) (aref lowlinks next))))
                     ((= 1 (aref in-stack next))
                      (setf (aref lowlinks v)
                            (min (aref lowlinks v) (aref ords next))))))
             (visit (v)
               (setf (aref ords v) ord
                     (aref lowlinks v) ord)
               (incf ord)
               (%push v)
               (cond ((= v source)
                      (loop for next below size1
                            when (= -1 (aref matching1 next))
                            do (frob v next)))
                     ((= v sink)
                      (loop for next below size2
                            unless (= -1 (aref matching2 next))
                            do (frob v (+ size1 next))))
                     ((and (< v size1) (= -1 (aref matching1 v)))
                      (dolist (next (aref graph1 v))
                        (declare ((integer 0 #.most-positive-fixnum) next))
                        (frob v (+ next size1))))
                     ((and (< v size1) (/= -1 (aref matching1 v)))
                      (frob v source)
                      (dolist (next (aref graph1 v))
                        (declare ((integer 0 #.most-positive-fixnum) next))
                        (unless (= next (aref matching1 v))
                          (frob v (+ next size1)))))
                     ((= -1 (aref matching2 (- v size1)))
                      (frob v sink))
                     (t
                      ;; (assert (/= -1 (aref matching2 (- v size1))))
                      (frob v (aref matching2 (- v size1)))))
               (when (= (aref lowlinks v) (aref ords v))
                 (loop for size of-type (integer 0 #.most-positive-fixnum) from 1
                       for w = (%pop)
                       do (setf (aref components w) comp-index)
                       until (= v w)
                       finally (setf (aref sizes comp-index) size)
                               (incf comp-index)))))
      (dotimes (v total-size)
        (when (= -1 (aref ords v))
          (visit v)))
      (values (subseq components 0 size1)
              (subseq components size1 (+ size1 size2))))))

(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  "NOTE: cannot read -2^62"
  (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))))))))

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

(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 match (tmp store counts target-col)
  (declare ((simple-array uint31 (* *)) tmp counts)
           (uint31 target-col))
  (destructuring-bind (n m) (array-dimensions tmp)
    (declare (uint8 n m))
    (let ((bgraph (make-bgraph m m))
          (lbase 0))
      (dotimes (y n)
        (dotimes (rnode m)
          (when (= +nan+ (aref tmp y rnode))
            (dotimes (loffset (aref counts y target-col))
              (bgraph-add-edge! bgraph (+ lbase loffset) rnode))))
        (incf lbase (aref counts y target-col)))
      (assert (= m (bgraph-build-matching! bgraph)))
      (let ((matching (bgraph-matching1 bgraph))
            (idx 0))
        (dotimes (y n)
          (dotimes (_ (aref counts y target-col))
            (setf (aref tmp y (aref matching idx))
                  (pop (aref store y target-col)))
            (incf idx)))))))


(defun solve (as)
  (declare ((simple-array uint31 (* *)) as))
  (destructuring-bind (n m) (array-dimensions as)
    (let ((tmp (make-array (list n m) :element-type 'uint31 :initial-element +nan+))
          (store (make-array (list n n) :element-type 'list :initial-element nil))
          (counts (make-array (list n n) :element-type 'uint31 :initial-element 0)))
      (dotimes (i n)
        (dotimes (j m)
          (let ((a (aref as i j)))
            (incf (aref counts i (floor a m)))
            (push a (aref store i (floor a m))))))
      (dotimes (col (array-dimension tmp 0))
        (match tmp store counts col))
      tmp)))

(defconstant +nan+ #x7fffffff)
(defun main ()
  (let* ((n (read))
         (m (read))
         (as (make-array (list n m) :element-type 'uint31 :initial-element 0)))
    (dotimes (i n)
      (dotimes (j m)
        (setf (aref as i j) (- (read-fixnum) 1))))
    (let ((res (solve as)))
      (write-string
       (with-output-to-string (*standard-output* nil :element-type 'base-char)
         (println-matrix res :key #'1+)
         (dotimes (j m)
           (dotimes (i1 n)
             (loop for i2 from (+ i1 1) below n
                   when (> (aref res i1 j) (aref res i2 j))
                   do (rotatef (aref res i1 j) (aref res i2 j)))))
         (println-matrix res :key #'1+))))))

(defun test (n m sample)
  (dotimes (_ sample)
    (let ((as (make-array (list n m) :element-type 'uint31 :initial-element 0)))
      (dotimes (i (* n m))
        (setf (aref (array-storage-vector as) i) i))
      (shuffle! (array-storage-vector as))
      (solve as))))
#-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 "2 6 
4 3 
5 1 
2 1 
4 3 
5 6
"
    (run "3 2
2 6
4 3
1 5
" nil)))
  (it.bese.fiveam:is
   (equal "1 4 7 10 
5 8 11 2 
9 12 3 6 
1 4 3 2 
5 8 7 6 
9 12 11 10
"
    (run "3 4
1 4 7 10
2 5 8 11
3 6 9 12
" nil))))