;;; Utils

(defmacro read-numbers-to-list ()
  `(read-from-string
    (concatenate 'string "(" (read-line) ")")))

(defmacro read-line-to-array (dimension)
  (if (< dimension 0)
      (error "invalid arguments for dimension.")
      `(make-array ,dimension :initial-contents (read-numbers-to-list))))

(defmacro read-line-to--char-list ()
  `(concatenate 'list (read-line)))

(defmethod make-cumlative-sum ((sequence list))
  (labels ((inner (sequence &optional (acc '(0)))
             (if (null sequence)
                 (reverse acc)
                 (inner (rest sequence) (cons (+ (first sequence)
                                                 (first acc))
                                              acc)))))
    (inner sequence)))

(defmethod princ-for-each-line ((sequence list))
  (labels ((inner (sequence)
             (if (null sequence)
                 nil
                 (progn
                   (fresh-line)
                   (princ (first sequence))
                   (inner (rest sequence))))))
    (inner sequence)))

(defmethod princ-for-each-line ((sequence array))
  (dotimes (i (length sequence))
    (fresh-line)
    (princ (aref sequence i))))

;;; Write code here

(defparameter *mod* (+ (expt 10 9) 7))

(defun calc-squared-sum (xs)
  (reduce #'+
          (mapcar (lambda (x)
                    (* x x))
                  xs)))

(defun sum (xs)
  (reduce #'+ xs))

(defun solve (n xs)
  (mod (floor (- (* (sum xs)
                    (sum xs))
                 (calc-squared-sum xs))
              2)
       *mod*))

(defun main ()
  (let ((n (read))
        (xs (read-numbers-to-list)))
    (format t "~a~%" (solve n xs))))

(main)

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 300 points

Problem Statement

Given are N integers A_1,\ldots,A_N.

Find the sum of A_i \times A_j over all pairs (i,j) such that 1\leq i < j \leq N, modulo (10^9+7).

Constraints

2 \leq N \leq 2\times 10^5

0 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} A_i A_j, modulo (10^9+7).

Sample Input 1

3
1 2 3

Sample Output 1

11

We have 1 \times 2 + 1 \times 3 + 2 \times 3 = 11.

Sample Input 2

4
141421356 17320508 22360679 244949

Sample Output 2

437235829

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


(defparameter den (+ (expt 10 9) 7))

(defun solve (lst)
  (/ (- (expt (apply #'+ lst) 2)
        (apply #'+ (mapcar #'* lst lst)))
     2))

(princ (mod (solve (loop repeat (read) collect (read)))
            den))


(defun f (list)
  (if (rest list)
      (multiple-value-bind (result sum)
          (f (rest list))
        (let ((val (first list)))
          (values (mod (+ result (* val sum)) 1000000007)
                  (let ((sum (+ val sum)))
                    (when (>= sum 1000000007)
                      (decf sum 1000000007))
                    sum))))
      (values 0 (first list))))

(format t "~A~%" (f (loop repeat (read) collect (read)))
        #+nil(loop with a = (loop repeat (read) collect (read))
              with result = 0
              for i2 on a
              for i = (first i2)
              while (cdr i2)
              do (incf result (* i (loop with result = 0
                                         for j in (rest i2)
                                         do (incf result j)
                                         finally (return result))))
              do (when (>= result 1000000007)
                   (setf result (mod result 1000000007)))
              finally (return result)))


(let* ((n (read))
    (a (make-array n :initial-element 1))
    (ans 0))

    (loop for i below n do
        (setf (aref a i) (rem (read) 1000000007))
    )
    (loop for i below (expt 2 n) do
        (let ((flg 0)
            (tmp 1))
            (loop for j below n  do
                (if (= (logand (ash i (- j)) #b1) 1)
                ;;bitが1だった場合の処理
                    (progn
                        (incf flg)
                        (if (<= flg 2)
                            (progn
                                (setq tmp (* tmp (aref a j)))
                                (if (>= tmp 1000000007)
                                    (setq tmp (rem tmp 1000000007))
                                )
                            )
                            (return)
                        )
                    )
                )
            )
            ;;i番目のパターンの処理
            (if (= flg 2)
                (incf ans tmp)
            )
        )
    )
    (format t "~D~%" (rem ans 1000000007))
)


(let* ((n (read))
    (a (make-array n :initial-element 1))
    (ans 0))

    (loop for i below n do
        (setf (aref a i) (rem (read) 1000000007))
    )
    (loop for i below (expt 2 n) do
        (let ((flg 0)
            (tmp 1))
            (loop for j below n unless (= flg 3) do
                (if (= (logand (ash i (- j)) #b1) 1)
                ;;bitが1だった場合の処理
                    (progn
                        (incf flg)
                        (if (<= flg 2)
                            (progn
                                (setq tmp (* tmp (aref a j)))
                                (if (>= tmp 1000000007)
                                    (setq tmp (rem tmp 1000000007))
                                )
                            )
                        )
                    )
                )
            )
            ;;i番目のパターンの処理
            (if (= flg 2)
                (incf ans tmp)
            )
        )
    )
    (format t "~D~%" (rem ans 1000000007))
)


(format t "~A~%"
        (loop with a = (loop repeat (read) collect (read))
              with result = 0
              for i2 on a
              for i = (first i2)
              while (cdr i2)
              do (incf result (* i (loop with result = 0
                                         for j in (rest i2)
                                         do (incf result j)
                                            (when (>= result 1000000007)
                                              (decf result 1000000007))
                                         finally (return result))))
              do (when (>= result 1000000007)
                   (setf result (mod result 1000000007)))
              finally (return result)))


;;; Utils

(defmacro read-numbers-to-list ()
  `(read-from-string
    (concatenate 'string "(" (read-line) ")")))

(defmacro read-line-to-array (dimension)
  (if (< dimension 0)
      (error "invalid arguments for dimension.")
      `(make-array ,dimension :initial-contents (read-numbers-to-list))))

(defmacro read-line-to--char-list ()
  `(concatenate 'list (read-line)))

(defmethod make-cumlative-sum ((sequence list))
  (labels ((inner (sequence &optional (acc '(0)))
             (if (null sequence)
                 (reverse acc)
                 (inner (rest sequence) (cons (+ (first sequence)
                                                 (first acc))
                                              acc)))))
    (inner sequence)))

(defmethod princ-for-each-line ((sequence list))
  (labels ((inner (sequence)
             (if (null sequence)
                 nil
                 (progn
                   (fresh-line)
                   (princ (first sequence))
                   (inner (rest sequence))))))
    (inner sequence)))

(defmethod princ-for-each-line ((sequence array))
  (dotimes (i (length sequence))
    (fresh-line)
    (princ (aref sequence i))))

;;; Write code here

(defparameter *mod* (+ (expt 10 9) 7))

(defun solve (n xs &optional (ans 0))
  (let ((xs-cum (rest (make-cumlative-sum xs))))
    (loop repeat (1- n)
       do (progn (setf ans (mod (+ ans
                                   (* (first xs-cum)
                                      (second xs)))
                                *mod*))
                 (pop xs-cum)
                 (pop xs)))
    ans))

(defun main ()
  (let ((n (read))
        (xs (read-numbers-to-list)))
    (format t "~a~%" (solve n xs))))

(main)


(format t "~A~%"
        (loop with a = (loop repeat (read) collect (read))
              with result = 0
              for i2 on a
              for i = (first i2)
              while (cdr i2)
              do (incf result (* i (loop for j2 on (rest i2)
                                         for j = (first j2)
                                         sum j)))
              do (when (>= result 1000000007)
                   (setf result (mod result 1000000007)))
              finally (return result)))


(format t "~A~%"
        (loop with a = (loop repeat (read) collect (read))
              with result = 0
              for i2 on a
              for i = (first i2)
              while (cdr i2)
              do (loop for j2 on (rest i2)
                            for j = (first j2)
                            do (incf result (* i j))
                               (when (>= result 1000000007)
                                 (setf result (mod result 1000000007))))
              finally (return result)))


(format t "~A~%"
        (loop with a = (loop repeat (read) collect (read))
              with result = 0
              for i2 on a
              for i = (first i2)
              while (cdr i2)
              do (loop for j2 on (rest i2)
                            for j = (first j2)
                            do (incf result (+ result (* i j)))
                               (when (>= result 1000000007)
                                 (setf result (mod result 1000000007))))
              finally (return result)))


(let* ((n (read))
    (a (make-array n :initial-element 1))
    (ans 0))

    (loop for i below n do
        (setf (aref a i) (rem (read) 1000000007))
    )
    (loop for i below (expt 2 n) do
        (let ((flg 0)
            (tmp 1))
            (loop for j below n do
                (if (= (logand (ash i (- j)) #b1) 1)
                ;;bitが1だった場合の処理
                    (progn
                        (incf flg)
                        (if (<= flg 2)
                            (progn
                                (setq tmp (* tmp (aref a j)))
                                (if (>= tmp 1000000007)
                                    (setq tmp (rem tmp 1000000007))
                                )
                            )
                        )
                    )
                )
            )
            ;;i番目のパターンの処理
            (if (= flg 2)
                (incf ans tmp)
            )
        )
    )
    (format t "~D~%" (rem ans 1000000007))
)


(let* ((n (read))
    (a (make-array n :initial-element 1))
    (ans 0))

    (loop for i below n do
        (setf (aref a i) (read))
    )
    (loop for i below (expt 2 n) do
        (let ((flg 0)
            (tmp 1))
            (loop for j below n do
                (if (= (logand (ash i (- j)) #b1) 1)
                ;;bitが1だった場合の処理
                    (progn
                        (incf flg)
                        (if (<= flg 2)
                            (progn
                                (setq tmp (* tmp (aref a j)))
                                (if (>= tmp 1000000007)
                                    (setq tmp (rem tmp 1000000007))
                                )
                            )
                        )
                    )
                )
            )
            ;;i番目のパターンの処理
            (if (= flg 2)
                (incf ans tmp)
            )
            (if (>= ans 1000000007)
                (setq ans (rem ans 1000000007))
            )
        )
    )
    (format t "~D~%" ans)
)


;エラトステネスの篩
(defun sieve (N)
  (if (<= N 1) nil
      (loop with lst = (cons 2 (loop for x from 3 to N by 2 collect x))
            and max = (isqrt N) and p1
            initially (setf p1 lst)
            if (or (null (cdr p1)) (< max (car p1))) return lst
            do (loop with p2 = p1 while (cdr p2)
                     if (zerop (mod (cadr p2) (car p1))) do (rplacd p2 (cddr p2))
                     do (setf p2 (cdr p2)))
            do (setf p1 (cdr p1)))))

(defun solve (N)
  (loop for x in (sieve N)
        with lst = (loop repeat N collect (read))
        if (< 1 (loop for y in lst count (zerop (mod y x))))
        return (if (= 1 (apply #'gcd lst)) "setwise coprime" "not coprime")
        finally (return "pairwise coprime")))

(princ (solve (read)))

Score : 500 points

Problem Statement

We have N integers. The i-th number is A_i.

\{A_i\} is said to be pairwise coprime when GCD(A_i,A_j)=1 holds for every pair (i, j) such that 1\leq i < j \leq N.

\{A_i\} is said to be setwise coprime when \{A_i\} is not pairwise coprime but GCD(A_1,\ldots,A_N)=1.

Determine if \{A_i\} is pairwise coprime, setwise coprime, or neither.

Here, GCD(\ldots) denotes greatest common divisor.

Constraints

2 \leq N \leq 10^6

1 \leq A_i\leq 10^6

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

If \{A_i\} is pairwise coprime, print pairwise coprime; if \{A_i\} is setwise coprime, print setwise coprime; if neither, print not coprime.

Sample Input 1

3
3 4 5

Sample Output 1

pairwise coprime

GCD(3,4)=GCD(3,5)=GCD(4,5)=1, so they are pairwise coprime.

Sample Input 2

3
6 10 15

Sample Output 2

setwise coprime

Since GCD(6,10)=2, they are not pairwise coprime. However, since GCD(6,10,15)=1, they are setwise coprime.

Sample Input 3

3
6 10 16

Sample Output 3

not coprime

GCD(6,10,16)=2, so they are neither pairwise coprime nor setwise coprime.


(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
;;;
;;; Extended Eratosthenes' sieve
;;;
;;; build: O(nloglogn)
;;; query: O(log(n))
;;; Reference:
;;; http://www.osak.jp/diary/diary_201310.html#20131017 (Japanese)
;;; https://cp-algorithms.com/algebra/prime-sieve-linear.html
;;;

(defpackage :cp/ext-eratosthenes
  (:use :cl)
  (:export #:make-minfactor-table #:factorize #:euler-phi))
(in-package :cp/ext-eratosthenes)

(declaim (ftype (function * (values (simple-array (unsigned-byte 31) (*)) &optional))
                make-minfactor-table))
(defun make-minfactor-table (sup)
  "Returns a vector of length SUP, whose (0-based) i-th value is the minimal
prime factor of i. (Corner case: 0th value is 0 and 1st value is 1.)"
  (declare (optimize (speed 3) (safety 0)))
  (check-type sup (integer 2 (#.array-total-size-limit)))
  (let ((table (make-array sup :element-type '(unsigned-byte 31))))
    ;; initialize
    (dotimes (i sup)
      (setf (aref table i) i))
    ;; p = 2
    (loop for even-num from 4 below sup by 2
          do (setf (aref table even-num) 2))
    ;; p >= 3
    (loop for p from 3 to (+ 1 (isqrt (- sup 1))) by 2
          when (= p (aref table p))
          do (loop for composite from (* p p) below sup by p
                   when (= (aref table composite) composite)
                   do (setf (aref table composite) p)))
    table))

(declaim (inline factorize))
(defun factorize (x minfactor-table)
  "Returns the associative list of prime factors of X, which is composed
of (<prime> . <exponent>). E.g. (factorize 100 <minfactor-table>) => '((2
. 2) (5 . 5)). The returned list is in ascending order
w.r.t. prime. Corner case: (factorize 0 table) => NIL.

MINFACTOR-TABLE := vector (MINFACTOR-TABLE[k] is the minimal prime factor of k)"
  (declare (fixnum x)
           (vector minfactor-table))
  (setq x (abs x))
  (when (<= x 1)
    (return-from factorize nil))
  (assert (< x (length minfactor-table)))
  (loop until (= x 1)
        for prime of-type (unsigned-byte 31) = (aref minfactor-table x)
        collect (loop for exponent of-type (unsigned-byte 31) from 0
                      do (multiple-value-bind (quot rem) (floor x prime)
                           (if (zerop rem)
                               (setf x quot)
                               (loop-finish)))
                      finally (return (cons prime exponent)))))

(defpackage :cp/read-fixnum
  (:use :cl)
  (:export #:read-fixnum))
(in-package :cp/read-fixnum)

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

;;;
;;; GCD and LCM
;;; Reference:
;;; https://lemire.me/blog/2013/12/26/fastest-way-to-compute-the-greatest-common-divisor/
;;;

(defpackage :cp/fast-gcd
  (:use :cl)
  (:export #:fast-gcd #:fast-lcm #:%fast-gcd))
(in-package :cp/fast-gcd)

(declaim (inline %fast-gcd fast-gcd fast-lcm)
         (ftype (function * (values (integer 0 #.most-positive-fixnum) &optional))
                %fast-gcd fast-gcd fast-lcm))
(defun %fast-gcd (u v)
  (declare ((integer 0 #.most-positive-fixnum) u v))
  (let ((shift (let ((x (logior u v)))
                 (- (integer-length (logand x (- x))) 1))))
    (declare (optimize (safety 0)))
    (setq u (ash u (- 1 (integer-length (logand u (- u))))))
    (loop (setq v (ash v (- 1 (integer-length (logand v (- v))))))
          (when (> u v)
            (rotatef u v))
          (decf v u)
          (when (zerop v)
            (return (the (integer 1 #.most-positive-fixnum)
                         (ash u shift)))))))

(defun fast-gcd (u v)
  (declare (optimize (speed 3))
           ((integer 0 #.most-positive-fixnum) u v))
  (cond ((zerop u) v)
        ((zerop v) u)
        (t (%fast-gcd u v))))

(defun fast-lcm (u v)
  (declare (optimize (speed 3))
           ((integer 0 #.most-positive-fixnum) u v))
  (if (or (zerop u) (zerop v))
      0
      (multiple-value-bind (max min)
          (if (> u v)
              (values u v)
              (values v u))
        (* (truncate max (%fast-gcd u v)) min))))

;; BEGIN_USE_PACKAGE
(eval-when (:compile-toplevel :load-toplevel :execute)
  (use-package :cp/fast-gcd :cl-user))
(eval-when (:compile-toplevel :load-toplevel :execute)
  (use-package :cp/read-fixnum :cl-user))
(eval-when (:compile-toplevel :load-toplevel :execute)
  (use-package :cp/ext-eratosthenes :cl-user))
(in-package :cl-user)

;;;
;;; Body
;;;

(defun main ()
  (declare #.cl-user::opt)
  (let* ((n (read))
         (as (loop repeat n collect (read-fixnum)))
         (table (make-minfactor-table 1000001))
         (marked (make-array 1000001 :element-type 'bit :initial-element 0))
         (pairwise-p t)
         (setwise-p (= 1 (reduce #'%fast-gcd as))))
    (declare (uint31 n))
    (block outer
      (dolist (a as)
        (let ((primes (factorize a table)))
          (loop for (p . exp) in primes
                when (= 1 (aref marked p))
                do (setq pairwise-p nil)
                   (return-from outer)
                do (setf (aref marked p) 1)))))
    (write-line (cond (pairwise-p "pairwise coprime")
                      (setwise-p "setwise coprime")
                      (t "not coprime")))))

#-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 "pairwise coprime
"
          (run "3
3 4 5
" nil)))
  (it.bese.fiveam:is
   (equal "setwise coprime
"
          (run "3
6 10 15
" nil)))
  (it.bese.fiveam:is
   (equal "not coprime
"
          (run "3
6 10 16
" nil))))


(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
;;;
;;; Extended Eratosthenes' sieve
;;;
;;; build: O(nloglogn)
;;; query: O(log(n))
;;; Reference:
;;; http://www.osak.jp/diary/diary_201310.html#20131017 (Japanese)
;;; https://cp-algorithms.com/algebra/prime-sieve-linear.html
;;;

(defpackage :cp/ext-eratosthenes
  (:use :cl)
  (:export #:make-minfactor-table #:factorize #:euler-phi))
(in-package :cp/ext-eratosthenes)

(declaim (ftype (function * (values (simple-array (integer 0 #.most-positive-fixnum) (*)) &optional))
                make-minfactor-table))
(defun make-minfactor-table (sup)
  "Returns a vector of length SUP, whose (0-based) i-th value is the minimal
prime factor of i. (Corner case: 0th value is 0 and 1st value is 1.)"
  (declare (optimize (speed 3) (safety 0)))
  (check-type sup (integer 2 (#.array-total-size-limit)))
  (let ((table (make-array sup :element-type '(integer 0 #.most-positive-fixnum))))
    ;; initialize
    (dotimes (i sup)
      (setf (aref table i) i))
    ;; p = 2
    (loop for even-num from 4 below sup by 2
          do (setf (aref table even-num) 2))
    ;; p >= 3
    (loop for p from 3 to (+ 1 (isqrt (- sup 1))) by 2
          when (= p (aref table p))
          do (loop for composite from (* p p) below sup by p
                   when (= (aref table composite) composite)
                   do (setf (aref table composite) p)))
    table))

(declaim (inline factorize))
(defun factorize (x minfactor-table)
  "Returns the associative list of prime factors of X, which is composed
of (<prime> . <exponent>). E.g. (factorize 100 <minfactor-table>) => '((2
. 2) (5 . 5)). The returned list is in ascending order
w.r.t. prime. Corner case: (factorize 0 table) => NIL.

MINFACTOR-TABLE := vector (MINFACTOR-TABLE[k] is the minimal prime factor of k)"
  (declare (fixnum x)
           (vector minfactor-table))
  (setq x (abs x))
  (when (<= x 1)
    (return-from factorize nil))
  (assert (< x (length minfactor-table)))
  (loop until (= x 1)
        for prime of-type (integer 0 #.most-positive-fixnum) = (aref minfactor-table x)
        collect (loop for exponent of-type (integer 0 #.most-positive-fixnum) from 0
                      do (multiple-value-bind (quot rem) (floor x prime)
                           (if (zerop rem)
                               (setf x quot)
                               (loop-finish)))
                      finally (return (cons prime exponent)))))

(declaim (inline euler-phi))
(defun euler-phi (x minfactor-table)
  (declare (fixnum x)
           (vector minfactor-table))
  (setq x (abs x))
  (assert (< x (length minfactor-table)))
  (let ((res x))
    (declare ((integer 0 #.most-positive-fixnum) res))
    (loop until (= x 1)
          for prime of-type (integer 0 #.most-positive-fixnum) = (aref minfactor-table x)
          do (decf res (floor res prime))
             (loop (multiple-value-bind (quot rem) (floor x prime)
                     (if (zerop rem)
                         (setq x quot)
                         (return)))))
    res))

(defpackage :cp/read-fixnum
  (:use :cl)
  (:export #:read-fixnum))
(in-package :cp/read-fixnum)

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

;; BEGIN_USE_PACKAGE
(eval-when (:compile-toplevel :load-toplevel :execute)
  (use-package :cp/read-fixnum :cl-user))
(eval-when (:compile-toplevel :load-toplevel :execute)
  (use-package :cp/ext-eratosthenes :cl-user))
(in-package :cl-user)

;;;
;;; Body
;;;

(defun main ()
  (declare #.cl-user::opt)
  (let* ((n (read))
         (table (make-minfactor-table 1000001))
         (as (loop repeat n collect (read-fixnum)))
         (marked (make-array 1000001 :element-type 'bit :initial-element 0))
         (pairwise-p t)
         (setwise-p (= 1 (reduce #'gcd as))))
    (declare (uint31 n))
    (block outer
      (dolist (a as)
        (let ((primes (factorize a table)))
          (loop for (p . exp) in primes
                when (= 1 (aref marked p))
                do (setq pairwise-p nil)
                   (return-from outer)
                do (setf (aref marked p) 1)))))
    (write-line
     (cond (pairwise-p "pairwise coprime")
           (setwise-p "setwise coprime")
           (t "not coprime")))))

#-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 "pairwise coprime
"
          (run "3
3 4 5
" nil)))
  (it.bese.fiveam:is
   (equal "setwise coprime
"
          (run "3
6 10 15
" nil)))
  (it.bese.fiveam:is
   (equal "not coprime
"
          (run "3
6 10 16
" nil))))


;;; Utils

(defmacro read-numbers-to-list ()
  `(read-from-string
    (concatenate 'string "(" (read-line) ")")))

(defmacro read-line-to-array (dimension)
  (if (< dimension 0)
      (error "invalid arguments for dimension.")
      `(make-array ,dimension :initial-contents (read-numbers-to-list))))

(defmacro read-line-to--char-list ()
  `(concatenate 'list (read-line)))

(defmethod make-cumlative-sum ((sequence list))
  (labels ((inner (sequence &optional (acc '(0)))
             (if (null sequence)
                 (reverse acc)
                 (inner (rest sequence) (cons (+ (first sequence)
                                                 (first acc))
                                              acc)))))
    (inner sequence)))

(defmethod princ-for-each-line ((sequence list))
  (labels ((inner (sequence)
             (if (null sequence)
                 nil
                 (progn
                   (fresh-line)
                   (princ (first sequence))
                   (inner (rest sequence))))))
    (inner sequence)))

(defmethod princ-for-each-line ((sequence array))
  (dotimes (i (length sequence))
    (fresh-line)
    (princ (aref sequence i))))

;;; Write code here

(defun factorize-number-to-lst (x)
  (assert (and (numberp x)
               (plusp x)))
  (labels
      ((inner (x)
         (if (= x 1)
             1)
         (let ((res nil)
               (f 2))
           (loop while (<= (* f f) x) do
                (if (zerop (mod x f))
                    (progn
                      (setf x (truncate x f))
                      (push f res))
                    (incf f))
              finally
                (progn
                  (when (/= x 1)
                    (push x res))
                  (return (reverse res)))))))
    (inner x)))

(defun setwise-p (xs)
  (=
   (reduce #'gcd xs)
   1))

(defun step-sum (sequence start end step)
  (assert (arrayp sequence))
  (labels ((inner (start end step &optional (acc 0))
             (if (< start end)
                 (inner (+ start step) end step (+ acc
                                                   (aref sequence start)))
                 acc)))
    (inner start end step)))

(defun pairwise-p (n xs)
  (assert (and (plusp n)
               (every #'numberp xs)))
  (let ((memo (make-array (1+ (expt 10 6))::initial-element 0))
        (flag t))
    (dotimes (i n)
      (incf (aref memo (first xs)))
      (pop xs))
    (let ((f 2))
      (loop while (<= f (expt 10 6)) do
           (when (> (step-sum memo f (1+ (expt 10 6)) f) 1)
             (setf flag nil))
           (incf f)
         finally
           (return flag)))))

(defun solve (n a)
  (cond
    ((pairwise-p n a) "pairwise coprime")
    ((setwise-p a)  "setwise coprime")
    (t "not coprime")))

(defun main ()
  (let ((n (read))
        (a (sort (read-numbers-to-list) #'<)))
    (format t "~a~%" (solve n a))))

(main)


;;; Utils

(defmacro read-numbers-to-list ()
  `(read-from-string
    (concatenate 'string "(" (read-line) ")")))

(defmacro read-line-to-array (dimension)
  (if (< dimension 0)
      (error "invalid arguments for dimension.")
      `(make-array ,dimension :initial-contents (read-numbers-to-list))))

(defmacro read-line-to--char-list ()
  `(concatenate 'list (read-line)))

(defmethod make-cumlative-sum ((sequence list))
  (labels ((inner (sequence &optional (acc '(0)))
             (if (null sequence)
                 (reverse acc)
                 (inner (rest sequence) (cons (+ (first sequence)
                                                 (first acc))
                                              acc)))))
    (inner sequence)))

(defmethod princ-for-each-line ((sequence list))
  (labels ((inner (sequence)
             (if (null sequence)
                 nil
                 (progn
                   (fresh-line)
                   (princ (first sequence))
                   (inner (rest sequence))))))
    (inner sequence)))

(defmethod princ-for-each-line ((sequence array))
  (dotimes (i (length sequence))
    (fresh-line)
    (princ (aref sequence i))))

;;; Write code here

(defun factorize-number-to-lst (x)
  (assert (and (numberp x)
               (plusp x)))
  (labels
      ((inner (x)
         (if (= x 1)
             1)
         (let ((res nil)
               (f 2))
           (loop while (<= (* f f) x) do
                (if (zerop (mod x f))
                    (progn
                      (setf x (truncate x f))
                      (push f res))
                    (incf f))
              finally
                (progn
                  (when (/= x 1)
                    (push x res))
                  (return (reverse res)))))))
    (inner x)))

(defun setwise-p (xs)
  (=
   (reduce #'gcd xs)
   1))

(defun step-sum (sequence start end step)
  (assert (arrayp sequence))
  (labels ((inner (start end step &optional (acc 0))
             (if (< start end)
                 (inner (+ start step) end step (+ acc
                                                   (aref sequence start)))
                 acc)))
    (inner start end step)))

(defun pairwise-p (n xs)
  (assert (and (plusp n)
               (every #'numberp xs)))
  (let ((memo (make-array (1+ (expt 10 6))::initial-element 0))
        (flag t))
    (dotimes (i n)
      (setf (aref memo (first xs)) 1)
      (pop xs))
    (let ((f 2))
      (loop while (<= f (expt 10 6)) do
           (when (> (step-sum memo f (1+ (expt 10 6)) f) 1)
             (setf flag nil))
           (incf f)
         finally
           (return flag)))))

(defun solve (n a)
  (cond
    ((pairwise-p n a) "pairwise coprime")
    ((setwise-p a)  "setwise coprime")
    (t "not coprime")))

(defun main ()
  (let ((n (read))
        (a (sort (read-numbers-to-list) #'<)))
    (format t "~a~%" (solve n a))))

(main)


;;; Utils

(defmacro read-numbers-to-list ()
  `(read-from-string
    (concatenate 'string "(" (read-line) ")")))

(defmacro read-line-to-array (dimension)
  (if (< dimension 0)
      (error "invalid arguments for dimension.")
      `(make-array ,dimension :initial-contents (read-numbers-to-list))))

(defmacro read-line-to--char-list ()
  `(concatenate 'list (read-line)))

(defmethod make-cumlative-sum ((sequence list))
  (labels ((inner (sequence &optional (acc '(0)))
             (if (null sequence)
                 (reverse acc)
                 (inner (rest sequence) (cons (+ (first sequence)
                                                 (first acc))
                                              acc)))))
    (inner sequence)))

(defmethod princ-for-each-line ((sequence list))
  (labels ((inner (sequence)
             (if (null sequence)
                 nil
                 (progn
                   (fresh-line)
                   (princ (first sequence))
                   (inner (rest sequence))))))
    (inner sequence)))

(defmethod princ-for-each-line ((sequence array))
  (dotimes (i (length sequence))
    (fresh-line)
    (princ (aref sequence i))))

;;; Write code here

(defun factorize-number-to-lst (x)
  (assert (and (numberp x)
               (plusp x)))
  (labels
      ((inner (x)
         (if (= x 1)
             1)
         (let ((res nil)
               (f 2))
           (loop while (<= (* f f) x) do
                (if (zerop (mod x f))
                    (progn
                      (setf x (truncate x f))
                      (push f res))
                    (incf f))
              finally
                (progn
                  (when (/= x 1)
                    (push x res))
                  (return (reverse res)))))))
    (inner x)))

(defun setwise-p (xs)
  (=
   (reduce #'gcd xs)
   1))

(defun step-sum (sequence start end step)
  (assert (arrayp sequence))
  (labels ((inner (start end step &optional (acc 0))
             (if (< start end)
                 (inner (+ start step) end step (+ acc
                                                   (aref sequence start)))
                 acc)))
    (inner start end step)))

(defun pairwise-p (n xs)
  (assert (and (plusp n)
               (every #'numberp xs)))
  (let ((memo (make-array (1+ (expt 10 6))::initial-element 0))
        (flag t))
    (dotimes (i n)
      (setf (aref memo (first xs)) 1)
      (pop xs))
    (let ((f 2))
      (loop while (<= f (expt 10 6)) do
           (when (> (step-sum memo f (expt 10 6) f) 1)
             (setf flag nil))
           (incf f)
         finally
           (return flag)))))

(defun solve (n a)
  (cond
    ((pairwise-p n a) "pairwise coprime")
    ((setwise-p a)  "setwise coprime")
    (t "not coprime")))

(defun main ()
  (let ((n (read))
        (a (sort (read-numbers-to-list) #'<)))
    (format t "~a~%" (solve n a))))

(main)


;;; Utils

(defmacro read-numbers-to-list ()
  `(read-from-string
    (concatenate 'string "(" (read-line) ")")))

(defmacro read-line-to-array (dimension)
  (if (< dimension 0)
      (error "invalid arguments for dimension.")
      `(make-array ,dimension :initial-contents (read-numbers-to-list))))

(defmacro read-line-to--char-list ()
  `(concatenate 'list (read-line)))

(defmethod make-cumlative-sum ((sequence list))
  (labels ((inner (sequence &optional (acc '(0)))
             (if (null sequence)
                 (reverse acc)
                 (inner (rest sequence) (cons (+ (first sequence)
                                                 (first acc))
                                              acc)))))
    (inner sequence)))

(defmethod princ-for-each-line ((sequence list))
  (labels ((inner (sequence)
             (if (null sequence)
                 nil
                 (progn
                   (fresh-line)
                   (princ (first sequence))
                   (inner (rest sequence))))))
    (inner sequence)))

(defmethod princ-for-each-line ((sequence array))
  (dotimes (i (length sequence))
    (fresh-line)
    (princ (aref sequence i))))

;;; Write code here

(defun factorize-number-to-lst (x)
  (assert (and (numberp x)
               (plusp x)))
  (labels
      ((inner (x)
         (if (= x 1)
             1)
         (let ((res nil)
               (f 2))
           (loop while (<= (* f f) x) do
                (if (zerop (mod x f))
                    (progn
                      (setf x (truncate x f))
                      (push f res))
                    (incf f))
              finally
                (progn
                  (when (/= x 1)
                    (push x res))
                  (return (reverse res)))))))
    (inner x)))

(defun setwise-p (xs)
  (=
   (reduce #'gcd xs)
   1))

(defun pairwise-p (n xs)
  (assert (and (plusp n)
               (every #'numberp xs)))
  (let ((memo (make-array (1+ (expt 10 6))::initial-element nil))
        (flag t))
    (dotimes (i n)
      (let* ((x (first xs))
             (ys (factorize-number-to-lst x)))
        (when (aref memo x)
          (setf flag nil))
        (loop while ys do
             (let* ((y (first ys))
                    (z y))
               (loop while (<= z (expt 10 6)) do
                    (setf (aref memo z) t)
                    (incf z y)))
             (pop ys)))
      (pop xs))
    flag))

(defun solve (n a)
  (cond
    ((pairwise-p n a) "pairwise coprime")
    ((setwise-p a)  "setwise coprime")
    (t "not coprime")))

(defun main ()
  (let ((n (read))
        (a (sort (read-numbers-to-list) #'<)))
    (format t "~a~%" (solve n a))))

(main)


#-swank (declaim (optimize (speed 3) (safety 0) (debug 0)))
#+swank (declaim (optimize (speed 3) (safety 0) (debug 0)))

(defconstant +mod+ 1000000007)

(declaim (inline println))
(defun println (obj &optional (stream *standard-output*))
  (let ((*read-default-float-format* 'double-float))
    (prog1
        (write obj :stream stream)
      (fresh-line stream))) body...)

(defmethod fast-sort ((sequence list) &key (test #'<))
  (declare (inline sort)
           (inline sb-impl::stable-sort-list))
  (sort sequence (lambda (x y)
                   (funcall test x y))))

(defmethod fast-sort ((sequence array) &key (test #'<))
  (declare (inline sort))
  (sort sequence (lambda (x y)
                   (funcall test x y))))

(defmacro read-numbers-to-list (size)
  `(loop repeat ,size collect (read)))

(defmacro read-numbers-to-array (size)
  `(progn
     (when (not (integerp ,size))
       (error "Size must be integer."))
     (when (< ,size 0)
       (error "Size must be plus or zero."))
     (make-array ,size :initial-contents (read-numbers-to-list ,size))))

(defmacro read-numbers-to-board (row-size column-size)
  (let ((board (gensym))
        (r (gensym))
        (c (gensym)))
    `(let ((,board (make-array '(,row-size ,column-size))))
       (dotimes (,r ,row-size)
         (dotimes (,c ,column-size)
           (setf (aref ,board ,r ,c) (read))))
       ,board)))

(defun princ-for-each-line (list)
  (format t "~{~a~&~}" list))

(defun unwrap (list)
  (format nil "~{~a~^ ~}" list))

(defmacro with-buffered-stdout (&body body)
  (let ((out (gensym)))
    `(let ((,out (make-string-output-stream :element-type 'base-char)))
       (let ((*standard-output* ,out))
         ,@body)
       (write-string (get-output-stream-string ,out)))))

;;; Write code here

(defun main ()
  (let* ((h (read))
         (w (read))
         (m (read))
         (mines (loop repeat m collect (cons (1- (read))
                                             (1- (read))))))
    (declare (fixnum h w m)
             (list mines))
    (let ((h-count (make-array h :element-type 'fixnum :adjustable nil))
          (w-count (make-array w :element-type 'fixnum :adjustable nil))
          (memo (make-hash-table :size m  :test #'eq)))
      (declare ((array fixnum 1) h-count w-count)
               (hash-table memo))
      (labels ((encode (y x)
                 (dpb x (byte 20 20) y)))

        (loop for mine of-type list in mines do
             (setf (gethash (encode (first mine) (rest mine)) memo) t))
        (loop for mine of-type list in mines do
             (incf (aref h-count (first mine)))
             (incf (aref w-count (rest mine))))
        (let* ((h-max (reduce #'max h-count))
               (w-max (reduce #'max w-count))
               (h-max-list (remove-if-not
                            (lambda (y)
                              (= (aref h-count y)
                                 h-max))
                            (loop for i below h collect i)))
               (w-max-list (remove-if-not
                            (lambda (x)
                              (= (aref w-count x)
                                 w-max))
                            (loop for i below w collect i))))
          (declare (fixnum h-max w-max)
                   (list h-max-list w-max-list))
          (let ((ans (1- (+ h-max w-max)))
                (flag nil))
            (declare (fixnum ans))
            (mapc (lambda (h)
                    (mapc (lambda (w)
                            (when (not (gethash (encode h w)
                                                memo))
                              (setq flag t)))
                          w-max-list))
                  h-max-list)
            (when flag
              (incf ans))
            (format t "~a~&" ans)))))))
#-swank (main)

Score : 500 points

Problem Statement

We have a two-dimensional grid with H \times W squares. There are M targets to destroy in this grid - the position of the i-th target is \left(h_i, w_i \right).

Takahashi will choose one square in this grid, place a bomb there, and ignite it. The bomb will destroy all targets that are in the row or the column where the bomb is placed. It is possible to place the bomb at a square with a target.

Takahashi is trying to maximize the number of targets to destroy. Find the maximum number of targets that can be destroyed.

Constraints

All values in input are integers.

1 \leq H, W \leq 3 \times 10^5

1 \leq M \leq \min\left(H\times W, 3 \times 10^5\right)

1 \leq h_i \leq H

1 \leq w_i \leq W

\left(h_i, w_i\right) \neq \left(h_j, w_j\right) \left(i \neq j\right)

Input

Input is given from Standard Input in the following format:

H W M
h_1 w_1
\vdots
h_M w_M

Output

Print the answer.

Sample Input 1

2 3 3
2 2
1 1
1 3

Sample Output 1

3

We can destroy all the targets by placing the bomb at \left(1, 2\right).

Sample Input 2

3 3 4
3 3
3 1
1 1
1 2

Sample Output 2

3

Sample Input 3

5 5 10
2 5
4 3
2 3
5 5
2 2
5 4
5 3
5 1
3 5
1 4

Sample Output 3

6


#-swank (declaim (optimize (speed 0) (safety 3) (debug 3)))
#+swank (declaim (optimize (speed 3) (safety 0) (debug 0)))

(defconstant +mod+ 1000000007)

(declaim (inline println))
(defun println (obj &optional (stream *standard-output*))
  (let ((*read-default-float-format* 'double-float))
    (prog1
        (write obj :stream stream)
      (fresh-line stream))) body...)

(defmethod fast-sort ((sequence list) &key (test #'<))
  (declare (inline sort)
           (inline sb-impl::stable-sort-list))
  (sort sequence (lambda (x y)
                   (funcall test x y))))

(defmethod fast-sort ((sequence array) &key (test #'<))
  (declare (inline sort))
  (sort sequence (lambda (x y)
                   (funcall test x y))))

(defmacro read-numbers-to-list (size)
  `(loop repeat ,size collect (read)))

(defmacro read-numbers-to-array (size)
  `(progn
     (when (not (integerp ,size))
       (error "Size must be integer."))
     (when (< ,size 0)
       (error "Size must be plus or zero."))
     (make-array ,size :initial-contents (read-numbers-to-list ,size))))

(defmacro read-numbers-to-board (row-size column-size)
  (let ((board (gensym))
        (r (gensym))
        (c (gensym)))
    `(let ((,board (make-array '(,row-size ,column-size))))
       (dotimes (,r ,row-size)
         (dotimes (,c ,column-size)
           (setf (aref ,board ,r ,c) (read))))
       ,board)))

(defun princ-for-each-line (list)
  (format t "~{~a~&~}" list))

(defun unwrap (list)
  (format nil "~{~a~^ ~}" list))

(defmacro with-buffered-stdout (&body body)
  (let ((out (gensym)))
    `(let ((,out (make-string-output-stream :element-type 'base-char)))
       (let ((*standard-output* ,out))
         ,@body)
       (write-string (get-output-stream-string ,out)))))

;;; Write code here

(defun main ()
  (let ((h (read))
        (w (read))
        (mines (loop repeat (read) collect (cons (1- (read))
                                                 (1- (read))))))
    (let ((h-count (make-array h))
          (w-count (make-array w)))
      (loop for m in mines do
           (incf (aref h-count (first m)))
           (incf (aref w-count (rest m))))
      (let* ((h-max (reduce #'max h-count))
             (w-max (reduce #'max w-count))
             (h-max-list (remove-if-not
                          (lambda (y)
                            (= (aref h-count y)
                               h-max))
                          (loop for i below h collect i)))
             (w-max-list (remove-if-not
                          (lambda (x)
                            (= (aref w-count x)
                               w-max))
                          (loop for i below w collect i))))
        (let ((ans (1- (+ h-max w-max)))
              (flag nil))
          (mapc (lambda (h)
                  (mapc (lambda (w)
                          (when (not (find (cons h w)
                                           mines
                                           :test #'equal))
                            (setq flag t)))
                        w-max-list))
                h-max-list)
          (when flag
            (incf ans))
          (format t "~a~&" ans))))))
#-swank (main)


(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/read-fixnum
  (:use :cl)
  (:export #:read-fixnum))
(in-package :cp/read-fixnum)

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

;; BEGIN_USE_PACKAGE
(eval-when (:compile-toplevel :load-toplevel :execute)
  (use-package :cp/read-fixnum :cl-user))
(in-package :cl-user)

;;;
;;; Body
;;;

(defun main ()
  (declare #.cl-user::opt)
  (let* ((h (read))
         (w (read))
         (m (read))
         (row-sums (make-array h :element-type 'uint31 :initial-element 0))
         (col-sums (make-array w :element-type 'uint31 :initial-element 0))
         (table (make-hash-table :size m :test #'equal)))
    (declare (uint31 h w m))
    (dotimes (i m)
      (let ((y (- (read-fixnum) 1))
            (x (- (read-fixnum) 1)))
        (incf (aref row-sums y))
        (incf (aref col-sums x))
        (setf (gethash (cons y x) table) t)))
    (let* ((row-max (reduce #'max row-sums))
           (col-max (reduce #'max col-sums))
           (col-nodes (loop for x below w
                            when (= (aref col-sums x) col-max)
                            collect x)))
      (declare (uint31 row-max col-max))
      (dotimes (row h)
        (when (= (aref row-sums row) row-max)
          (dolist (col col-nodes)
            (unless (gethash (cons row col) table)
              (println (+ row-max col-max))
              (return-from main)))))
      (println (+ row-max col-max -1)))))

#-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 "3
"
          (run "2 3 3
2 2
1 1
1 3
" nil)))
  (it.bese.fiveam:is
   (equal "3
"
          (run "3 3 4
3 3
3 1
1 1
1 2
" nil)))
  (it.bese.fiveam:is
   (equal "6
"
          (run "5 5 10
2 5
4 3
2 3
5 5
2 2
5 4
5 3
5 1
3 5
1 4
" nil))))


(let* ((h (read))
       (w (read))
       (m (read))
       (pos (make-hash-table :test 'equal :size m))
       (h-num (make-array (list h) :initial-element nil))
       (w-num (make-array (list w) :initial-element nil))
       (stack (make-array (list m) :adjustable t :fill-pointer 0))
       (p 0)
       (ans 0))
  (loop :for i :from 1 :to h
        :do (setf (aref h-num (1- i)) (cons i 0)))
  (loop :for j :from 1 :to w
        :do (setf (aref w-num (1- j)) (cons j 0)))
  (loop :for k :from 1 :to m
        :for i := (read)
        :for j := (read)
        :do (incf (cdr (aref h-num (1- i))))
        :do (incf (cdr (aref w-num (1- j))))
        :do (setf (gethash (cons i j) pos) t))
  ;
  (setf h-num (sort h-num (lambda (a b) (> (cdr a) (cdr b)))))
  (setf w-num (sort w-num (lambda (a b) (> (cdr a) (cdr b)))))
  ;
  (vector-push-extend (cons 0 0) stack)
  (defun s (i j)
    (let ((x (aref h-num i))
          (y (aref w-num j)))
      (cond ((gethash (cons (car x) (car y)) pos)
             (when (and (< (1+ i) h) (= (cdr x) (cdr (aref h-num (1+ i)))))
               (vector-push-extend (cons (1+ i) j) stack))
             (when (and (< (1+ j) w) (= (cdr y) (cdr (aref w-num (1+ j)))))
               (vector-push-extend (cons i (1+ j)) stack))
             (setf ans (max ans (+ (cdr x) (cdr y) -1))))
            (t
             (setf ans (max ans (+ (cdr x) (cdr y))))))))
  (loop :while (= (length stack) p)
        :for arg := (aref stack p)
        :do (incf p)
        :do (s (car arg) (cdr arg)))
  (format t "~A~%" ans))


(let* ((h (read))
       (w (read))
       (m (read))
       (pos (make-hash-table :test 'equal :size m))
       (h-num (make-array (list h) :initial-element nil))
       (w-num (make-array (list w) :initial-element nil))
       (stack nil)
       (ans 0))
  (loop :for i :from 1 :to h
        :do (setf (aref h-num (1- i)) (cons i 0)))
  (loop :for j :from 1 :to w
        :do (setf (aref w-num (1- j)) (cons j 0)))
  (loop :for k :from 1 :to m
        :for i := (read)
        :for j := (read)
        :do (incf (cdr (aref h-num (1- i))))
        :do (incf (cdr (aref w-num (1- j))))
        :do (setf (gethash (cons i j) pos) t))
  ;
  (setf h-num (sort h-num (lambda (a b) (> (cdr a) (cdr b)))))
  (setf w-num (sort w-num (lambda (a b) (> (cdr a) (cdr b)))))
  ;
  (push (cons 0 0) stack)
  (defun s (i j)
    (let ((x (aref h-num i))
          (y (aref w-num j)))
      (cond ((gethash (cons (car x) (car y)) pos)
             (when (and (< (1+ i) h) (= (cdr x) (cdr (aref h-num (1+ i)))))
               (push (cons (1+ i) j) stack))
             (when (and (< (1+ j) w) (= (cdr y) (cdr (aref w-num (1+ j)))))
               (push (cons i (1+ j)) stack))
             (setf ans (max ans (+ (cdr x) (cdr y) -1))))
            (t
             (setf ans (max ans (+ (cdr x) (cdr y))))))))
  (loop :while stack
        :for arg := (pop stack)
        :do (s (car arg) (cdr arg)))
  (format t "~A~%" ans))


(let* ((h (read))
       (w (read))
       (m (read))
       (pos (make-hash-table :test 'equal :size m))
       (h-num (make-array (list h) :initial-element nil))
       (w-num (make-array (list w) :initial-element nil))
       (stack nil)
       (ans 0))
  (loop :for i :from 1 :to h
        :do (setf (aref h-num (1- i)) (cons i 0)))
  (loop :for j :from 1 :to w
        :do (setf (aref w-num (1- j)) (cons j 0)))
  (loop :for k :from 1 :to m
        :for i := (read)
        :for j := (read)
        :do (incf (cdr (aref h-num (1- i))))
        :do (incf (cdr (aref w-num (1- j))))
        :do (setf (gethash (cons i j) pos) t))
  ;
  (setf h-num (sort h-num (lambda (a b) (> (cdr a) (cdr b)))))
  (setf w-num (sort w-num (lambda (a b) (> (cdr a) (cdr b)))))
  ;
  (push (cons 0 0) stack)
  (defun s (i j)
    (let ((x (aref h-num i))
          (y (aref w-num j)))
      (cond ((gethash (cons (car x) (car y)) pos)
             (when (< (1+ i) h)
               (push (cons (1+ i) j) stack))
             (when (< (1+ j) w)
               (push (cons i (1+ j)) stack))
             (setf ans (max ans (+ (cdr x) (cdr y) -1))))
            (t
             (setf ans (max ans (+ (cdr x) (cdr y))))))))
  (loop :while stack
        :for arg := (pop stack)
        :do (s (car arg) (cdr arg)))
  (format t "~A~%" ans))


(let* ((h (read))
       (w (read))
       (m (read))
       (pos (make-hash-table :test 'equal :size m))
       (h-num (make-array (list h) :initial-element nil))
       (w-num (make-array (list w) :initial-element nil)))
  (loop :for i :from 1 :to h
        :do (setf (aref h-num (1- i)) (cons i 0)))
  (loop :for j :from 1 :to w
        :do (setf (aref w-num (1- j)) (cons j 0)))
  (loop :for k :from 1 :to m
        :for i := (read)
        :for j := (read)
        :do (incf (cdr (aref h-num (1- i))))
        :do (incf (cdr (aref w-num (1- j))))
        :do (setf (gethash (cons i j) pos) t))
  ;
  (setf h-num (sort h-num (lambda (a b) (> (cdr a) (cdr b)))))
  (setf w-num (sort w-num (lambda (a b) (> (cdr a) (cdr b)))))
  ;
  (defun s (i j)
    (let ((x (aref h-num i))
          (y (aref w-num j)))
      (cond ((gethash (cons (car x) (car y)) pos)
             (max (s (min (1+ i) (1- h)) j)
                  (s i (min (1+ j) (1- w)))
                  (+ (cdr x) (cdr y) -1)))
            (t
             (+ (cdr x) (cdr y))))))
  (format t "~A~%" (s 0 0)))


(let* ((h (read))
       (w (read))
       (m (read))
       (pos (make-hash-table :test 'equal :size m))
       (h-num (make-array (list (1+ h)) :initial-element 0))
       (w-num (make-array (list (1+ w)) :initial-element 0))
       (h-list nil)
       (w-list nil))
  (loop :for k :from 1 :to m
        :for i := (read)
        :for j := (read)
        :do (incf (aref h-num i))
        :do (incf (aref w-num j))
        :do (setf (gethash (cons i j) pos) t))
  ;
  (setf h-list (sort (loop :for i :from 1 :to h
                           :collect (cons i (aref h-num i)))
                     (lambda (a b) (> (cdr a) (cdr b)))))
  (setf w-list (sort (loop :for j :from 1 :to w
                           :collect (cons j (aref w-num j)))
                     (lambda (a b) (> (cdr a) (cdr b)))))
  ;
  (defun s (i j)
    (let ((x (car i))
          (y (car j)))
      (unless x
        (setf x (cons 0 0)))
      (unless y
        (setf y (cons 0 0)))
      (cond ((gethash (cons (car x) (car y)) pos)
             (max (s (cdr i) j)
                  (s i (cdr j))
                  (+ (cdr x) (cdr y) -1)))
            (t
             (+ (cdr x) (cdr y))))))
  (format t "~A~%" (s h-list w-list)))


(defun main (price)
  (let ((remainder (rem price 1000)))
    (princ
     (if (not (zerop remainder)) (- 1000 remainder) 0))))

(main (read))

Score : 100 points

Problem Statement

We will buy a product for N yen (the currency of Japan) at a shop.

If we use only 1000-yen bills to pay the price, how much change will we receive?

Assume we use the minimum number of bills required.

Constraints

1 \leq N \leq 10000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the amount of change as an integer.

Sample Input 1

1900

Sample Output 1

100

We will use two 1000-yen bills to pay the price and receive 100 yen in change.

Sample Input 2

3000

Sample Output 2

0

We can pay the exact price.


(loop :for k :from 0 :upto 1000
      :with n := (read)
      :if (= 0 (mod (+ k n) 1000))
        :do(princ k))


(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
(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 main ()
  (let* ((n (read)))
    (println (- (* 1000 (ceiling n 1000)) n))))

#-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 "1900
"
    "100
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3000
"
    "0
")))


(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

(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
;;;
;;; Sort multiple vectors
;;;

;; TODO: throw an error if there are two ore more identical vectors in the given
;; vectors

(declaim (inline %median3))
(defun %median3 (x y z)
  (if (> x y)
      (if (> y z)
          y
          (if (> z x)
              x
              z))
      (if (> z y)
          y
          (if (> x z)
              x
              z))))

(defun parallel-sort! (vector vector1 vector2 end)
  (declare #.OPT
           ((simple-array int32 (*)) vector)
           ((simple-array t (*)) vector1 vector2)
           ((integer 0 #.array-total-size-limit) end))
  (labels
      ((recur (left right)
         (declare ((integer -1 #.array-total-size-limit) left right))
         (when (< left right)
           (let* ((l left)
                  (r right)
                  (pivot (%median3 (aref vector l)
                                   (aref vector (ash (+ l r) -1))
                                   (aref vector r))))
             (declare ((integer 0 #.most-positive-fixnum) l r))
             (loop (loop while (> (aref vector l) pivot)
                         do (incf l 1))
                   (loop while (> pivot (aref vector r))
                         do (decf r 1))
                   (when (>= l r)
                     (return))
                   (rotatef (aref vector l) (aref vector r))
                   (rotatef (aref vector1 l) (aref vector1 r))
                   (rotatef (aref vector2 l) (aref vector2 r))
                   (incf l 1)
                   (decf r 1))
             (recur left (- l 1))
             (recur (+ r 1) right)))))
    (recur 0 (- end 1))
    vector))

(declaim (inline bisect-left))
(defun bisect-left (target value &key (start 0) end (order #'<) (key #'identity))
  "TARGET := vector | function (taking an integer argument)
ORDER := strict order

Analogue of lower_bound() of C++ or bisect_left() of Python: Returns the
smallest index (or input) i that fulfills TARGET[i] >= VALUE, where '>=' is the
complement of ORDER. In other words, this function returns the leftmost index at
which VALUE can be inserted with keeping the order. Therefore, TARGET must be
monotonically non-decreasing with respect to ORDER.

- This function returns END if VALUE exceeds TARGET[END-1].
- The range [START, END) is half-open.
- END must be explicitly specified if TARGET is function.
- KEY is applied to each element of TARGET before comparison."
  (declare (function key order)
           (integer start)
           ((or null integer) end))
  (macrolet
      ((frob (accessor &optional declaration)
         `(labels
              ((%bisect-left (ng ok)
                 ;; TARGET[OK] >= VALUE always holds (assuming
                 ;; TARGET[END] = +infinity)
                 ,@(when declaration (list declaration))
                 (if (<= (- ok ng) 1)
                     ok
                     (let ((mid (ash (+ ng ok) -1)))
                       (if (funcall order (funcall key (,accessor target mid)) value)
                           (%bisect-left mid ok)
                           (%bisect-left ng mid))))))
            (assert (<= start end))
            (%bisect-left (- start 1) end))))
    (etypecase target
      (vector
       (let ((end (or end (length target))))
         (frob aref (declare ((integer -1 (#.most-positive-fixnum)) ng ok)))))
      (function
       (assert end () "Requires END argument if TARGET is a function.")
       (frob funcall)))))

(declaim (inline bisect-right))
(defun bisect-right (target value &key (start 0) end (order #'<) (key #'identity))
  "TARGET := vector | function (taking an integer argument)
ORDER := strict order

Analogue of upper_bound() of C++ or bisect_right() of Python: Returns the
smallest index (or input) i that fulfills TARGET[i] > VALUE. In other words,
this function returns the rightmost index at which VALUE can be inserted with
keeping the order. Therefore, TARGET must be monotonically non-decreasing with
respect to ORDER.

- This function returns END if VALUE >= TARGET[END-1].
- The range [START, END) is half-open.
- END must be explicitly specified if TARGET is function.
- KEY is applied to each element of TARGET before comparison."
  (declare (function key order)
           (integer start)
           ((or null integer) end))
  (macrolet
      ((frob (accessor &optional declaration)
         `(labels
              ((%bisect-right (ng ok)
                 ;; TARGET[OK] > VALUE always holds (assuming
                 ;; TARGET[END] = +infinity)
                 ,@(when declaration (list declaration))
                 (if (<= (- ok ng) 1)
                     ok
                     (let ((mid (ash (+ ng ok) -1)))
                       (if (funcall order value (funcall key (,accessor target mid)))
                           (%bisect-right ng mid)
                           (%bisect-right mid ok))))))
            (assert (<= start end))
            (%bisect-right (- start 1) end))))
    (etypecase target
      (vector
       (let ((end (or end (length target))))
         (frob aref (declare ((integer -1 (#.array-total-size-limit)) ng ok)))))
      (function
       (assert end () "Requires END argument if TARGET is a function.")
       (frob funcall)))))

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

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

(defstruct state
  (d 0 :type uint16)
  (cs nil :type (simple-array uint8 (*)))
  (ss nil :type (simple-array uint32 (365 26)))
  (schedule nil :type (simple-array uint8 (*)))
  (history-table nil :type (simple-array (simple-array int16 (*)) (26)))
  (ends nil :type (simple-array uint16 (*)))
  (score 0 :type fixnum))

(defun make-state-from (d cs ss schedule)
  (declare #.OPT
           (uint32 d)
           ((simple-array uint8 (*)) cs schedule)
           ((simple-array uint32 (* *)) ss))
  (let ((history-table (make-array 26 :element-type '(simple-array int16 (*))))
        (ends (make-array 26 :element-type 'uint16 :initial-element 1)))
    (dotimes (i 26)
      (let ((history (make-array (+ d 2) :element-type 'int16)))
        (setf (aref history 0) -1)
        (setf (aref history-table i) history)))
    (dotimes (i d)
      (let ((type (aref schedule i)))
        (setf (aref (aref history-table type) (aref ends type)) i)
        (incf (aref ends type))))
    (dotimes (i 26)
      (setf (aref (aref history-table i) (aref ends i)) d)
      (incf (aref ends i)))
    (let* ((prevs (make-array 26 :element-type 'int32 :initial-element -1))
           (score 0))
      (declare (fixnum score))
      (dotimes (i d)
        (let ((type (aref schedule i)))
          (incf score (aref ss i type))
          (setf (aref prevs type) i)
          (dotimes (j 26)
            (decf score (* (aref cs j) (- i (aref prevs j)))))))
      (make-state :d d
                  :cs cs
                  :ss ss
                  :schedule schedule
                  :history-table history-table
                  :ends ends
                  :score score))))

(defun state-update! (state day new-type &optional old-pos new-pos)
  (declare #.OPT
           (uint16 day new-type)
           ((or null uint16) old-pos new-pos))
  (symbol-macrolet ((score (state-score state))
                    (cs (state-cs state))
                    (ss (the (simple-array uint32 (365 26)) (state-ss state)))
                    (history-table (state-history-table state))
                    (ends (state-ends state)))
    (let* ((old-type (aref (state-schedule state) day))
           (old-history (aref history-table old-type))
           (new-history (aref history-table new-type)))
      (declare ((array int16 (*)) old-history new-history))
      ;; delete old type
      (decf score (aref ss day old-type))
      (unless old-pos
        (setq old-pos (floor (the uint31 (* day (- (aref ends old-type) 1))) 365))
        (loop while (< (aref old-history old-pos) day)
              do (incf old-pos))
        (loop while (< day (aref old-history old-pos))
              do (decf old-pos)))
      (let* ((pos old-pos)
             (prev-day (aref old-history (- pos 1)))
             (next-day (aref old-history (+ pos 1))))
        ;; (assert (= day (aref old-history pos)))
        (decf score (* (aref cs old-type) (- day prev-day) (- next-day day)))
        (loop for i from pos below (aref ends old-type)
              do (rotatef (aref old-history i) (aref old-history (+ i 1))))
        (decf (aref ends old-type)))
      ;; add new type
      (incf score (aref ss day new-type))
      (unless new-pos
        (setq new-pos (floor (the uint31 (* day (- (aref ends new-type) 1))) 365))
        (loop while (< (aref new-history new-pos) day)
              do (incf new-pos))
        (loop while (< day (aref new-history new-pos))
              do (decf new-pos))
        (incf new-pos))
      ;; (unless new-pos
      ;;   (setq new-pos (bisect-left new-history day :end (aref ends new-type))))
      (let* ((pos new-pos)
             (next-day (aref new-history pos))
             (prev-day (aref new-history (- pos 1))))
        ;; (assert (< day (aref new-history pos)))
        (incf score (* (aref cs new-type) (- day prev-day) (- next-day day)))
        (setf (aref new-history (aref ends new-type)) day)
        (loop for i from (aref ends new-type) above pos
              do (rotatef (aref new-history i) (aref new-history (- i 1))))
        (incf (aref ends new-type)))
      (setf (state-score state) score)
      (setf (aref (state-schedule state) day) new-type)
      (values state old-pos new-pos))))

(defun state-eval-update (state day new-type)
  (declare #.OPT
           (uint16 day new-type))
  (symbol-macrolet ((cs (state-cs state))
                    (ss (the (simple-array uint32 (365 26)) (state-ss state)))
                    (history-table (state-history-table state))
                    (ends (state-ends state)))
    (let* ((score (state-score state))
           (old-type (aref (state-schedule state) day))
           (old-history (aref history-table old-type))
           (new-history (aref history-table new-type)))
      (declare (int32 score)
               ((array int16 (*)) old-history new-history))
      ;; delete old type
      (decf score (aref ss day old-type))
      (let ((old-pos (floor (the uint31 (* day (- (aref ends old-type) 1))) 365)))
        (declare (uint31 old-pos))
        (loop while (< (aref old-history old-pos) day)
              do (incf old-pos))
        (loop while (< day (aref old-history old-pos))
              do (decf old-pos))
        (let* ((prev-day (aref old-history (- old-pos 1)))
               (next-day (aref old-history (+ old-pos 1))))
          ;; (assert (= day (aref old-history old-pos)))
          (decf score (* (aref cs old-type) (- day prev-day) (- next-day day)))
          ;; add new type
          (incf score (aref ss day new-type))
          (let ((new-pos (floor (the uint31 (* day (- (aref ends new-type) 1))) 365)))
            (declare (uint31 new-pos))
            (loop while (< (aref new-history new-pos) day)
                  do (incf new-pos))
            (loop while (< day (aref new-history new-pos))
                  do (decf new-pos))
            (incf new-pos)
            (let* ((next-day (aref new-history new-pos))
                   (prev-day (aref new-history (- new-pos 1))))
              ;; (assert (< day (aref new-history new-pos)))
              (incf score (* (aref cs new-type) (- day prev-day) (- next-day day)))
              (values score old-pos new-pos))))))))

(declaim (inline calc-prob))
(defun calc-prob (prev-score new-score temp)
  (declare (int32 prev-score new-score)
           (double-float temp))
  (if (>= new-score prev-score)
      1d0
      (let ((x (/ (- new-score prev-score) temp)))
        (+ (* x (+ (* x (+ (* x (+ (* x (+ (* x #.(float 1/120 1d0)) #.(float 1/24 1d0))) #.(float 1/6 1d0))) #.(float 1/2 1d0))) 1d0)) 1d0))))

(defun anneal (state &optional (time 1.86d0))
  (declare #.OPT
           (double-float time))
  (let* ((opt-schedule (copy-seq (state-schedule state)))
         (opt-score (state-score state))
         (start-temp 2000d0)
         (end-temp 150d0)
         (loop-count 0)
         (rem-time time))
    (declare (fixnum loop-count opt-score)
             (double-float start-temp end-temp rem-time))
    (sb-int:with-progressive-timeout (rem-time :seconds time)
      (loop
        (incf loop-count)
        (when (zerop (logand #.(- (ash 2 7) 1) loop-count))
          (setq rem-time (float (rem-time) 1d0)))
        (when (zerop rem-time)
          (return))
        (if (zerop (random 4))
            (let* ((day (random (state-d state)))
                   (old-type (aref (state-schedule state) day))
                   (new-type (random 26))
                   (old-score (state-score state)))
              (unless (= old-type new-type)
                ;; tmp. update
                (multiple-value-bind (new-score old-pos new-pos)
                    (state-eval-update state day new-type)
                  (let* ((temp (+ end-temp (/ (* rem-time (- start-temp end-temp)) time)))
                         (prob (calc-prob old-score new-score temp)))
                    (declare (double-float temp))
                    (when (<= (random 1.0) prob)
                      (state-update! state day new-type old-pos new-pos)
                      (when (> new-score opt-score)
                        ;; #>rem-time
                        (setq opt-schedule (copy-seq (state-schedule state))
                              opt-score new-score)))))))
            (let* ((width (+ 1 (random 16)))
                   (day (random (- (state-d state) width)))
                   (type1 (aref (state-schedule state) day))
                   (type2 (aref (state-schedule state) (+ day width)))
                   (old-score (state-score state)))
              (unless (= type1 type2)
                (multiple-value-bind (_ old-pos1 new-pos1)
                    (state-update! state day type2)
                  (multiple-value-bind (new-score old-pos2 new-pos2)
                      (state-eval-update state (+ day width) type1)
                    (let* ((temp (+ end-temp (/ (* rem-time (- start-temp end-temp)) time)))
                           (prob (calc-prob old-score new-score temp)))
                      (declare (double-float temp))
                      (if (<= (random 1.0) prob)
                          (progn
                            (state-update! state (+ day width) type1 old-pos2 new-pos2)
                            (when (> new-score opt-score)
                              ;; #>rem-time
                              (setq opt-schedule (copy-seq (state-schedule state))
                                    opt-score new-score)))
                          (state-update! state day type1 new-pos1 old-pos1))))))))))
    #>loop-count
    (values opt-schedule opt-score)))

(defun print* (state)
  (write-string
   (with-output-to-string (*standard-output* nil :element-type 'base-char)
     (loop for x across state
           do (println (+ x 1))))))

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defconstant +beam-width+ 100))

(defun make-initial-schedule (d cs ss)
  (declare #.OPT
           (uint16 d)
           ((simple-array uint8 (*)) cs)
           ((simple-array uint32 (365 26)) ss))
  (let* (;; score schedule prevs
         (que1 (make-array #.(* +beam-width+ 26) :element-type 'int32))
         (que2 (make-array #.(* +beam-width+ 26) :element-type t))
         (que3 (make-array #.(* +beam-width+ 26) :element-type t))
         (new-que1 (make-array #.(* +beam-width+ 26) :element-type 'int32))
         (new-que2 (make-array #.(* +beam-width+ 26) :element-type t))
         (new-que3 (make-array #.(* +beam-width+ 26) :element-type t))
         (end 0)
         (new-end 0))
    (declare ((simple-array int32 (*)) que1 new-que1)
             ((simple-array t (*)) que2 new-que2 que3 new-que3)
             (uint31 end new-end))
    (setf (aref que1 0) 0
          (aref que2 0) nil
          (aref que3 0) (make-array 26 :element-type 'int16 :initial-element -1))
    (incf end)
    (dotimes (i d)
      (loop for j below (min +beam-width+ end)
            for base-score of-type int32 = (aref que1 j)
            for schedule of-type list = (aref que2 j)
            for prevs of-type (simple-array int16 (*)) = (aref que3 j)
            do (dotimes (type 26)
                 (decf base-score (* (aref cs type) (- i (aref prevs type)))))
               (dotimes (type 26)
                 (let ((new-score (+ base-score
                                     (aref ss i type)
                                     (* (aref cs type) (- i (aref prevs type)))))
                       (new-prevs (copy-seq prevs)))
                   (setf (aref new-prevs type) i)
                   (setf (aref new-que1 new-end) new-score
                         (aref new-que2 new-end) (cons type schedule)
                         (aref new-que3 new-end) new-prevs)
                   (incf new-end))))
      (parallel-sort! new-que1 new-que2 new-que3 new-end)
      (rotatef que1 new-que1)
      (rotatef que2 new-que2)
      (rotatef que3 new-que3)
      (setq end new-end
            new-end 0))
    (coerce (reverse (aref que2 0)) '(simple-array uint8 (*)))))

(defun main ()
  (declare #.OPT)
  (let* ((d (read))
         (cs #-swank (sb-int:make-static-vector 26)
             #+swank (make-array 26 :element-type 'uint8 :initial-element 0))
         (ss (make-array (list d 26) :element-type 'uint32 :initial-element 0)))
    (dotimes (i 26)
      (setf (aref cs i) (read-fixnum)))
    (dotimes (i d)
      (dotimes (j 26)
        (setf (aref ss i j) (read-fixnum))))
    ;; #>ss
    (let* ((init-schedule (make-initial-schedule d cs ss))
           (init-state (make-state-from d cs ss init-schedule)))
      ;; #>init-state
      ;; #>(state-score init-state)
      ;; (print* init-state)
      ;; (loop for x across (initialize-scores d cs ss init-state) sum x)
      (multiple-value-bind (schedule score) (anneal init-state)
        ;; (let ((result-state (make-state-from d cs ss schedule)))
        ;;   (assert (= score (state-score result-state))))
        (print* schedule)
        score))))

;; #+linux
;; (eval-when (:compile-toplevel :load-toplevel :execute)
;;   (require :sb-sprof))
;; #+linux
;; (sb-sprof:start-profiling)

#-swank (main)

;; #+linux
;; (progn
;;   (sb-sprof:stop-profiling)
;;   (sb-sprof:report))

;;;
;;; 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 (seed)
  (uiop:with-output-file (out *dat-pathname* :if-exists :supersede)
    (let ((state (seed-random-state seed)))
      (format out "365~%")
      (dotimes (i 26)
        (println (random 101 state) out))
      (dotimes (i 365)
        (dotimes (j 26)
          (println (random 20001 state) out))))))

#+swank
(defun bench ()
  (let ((*random-state* (seed-random-state 0)))
    (loop for i below 20
          do (gen-dat i)
             (setq *random-state* (seed-random-state (+ i 1)))
          sum #>(run *dat-pathname*))))

Problem Statement

AtCoder currently hosts three types of contests: ABC, ARC, and AGC. As the number of users has grown, in order to meet the needs of more users, AtCoder has decided to increase the number of contests to 26 types, from AAC to AZC. For convenience, we number these 26 types as type 1 through type 26. AtCoder wants to schedule contests for D days so that user satisfaction is as high as possible. For every day, AtCoder will hold exactly one contest, and each contest will end on that day. The satisfaction is calculated as follows.

The satisfaction at the beginning of day 1 is 0. Satisfaction can be negative.

Holding contests increases satisfaction. The amount of increase will vary depending on a variety of factors. Specifically, we know in advance that holding a contest of type i on day d will increase the satisfaction by s_{d,i}.

If a particular type of contest is not held for a while, the satisfaction decreases. Each contest type i has an integer c_i, and at the end of each day d=1,2,...,D, the satisfaction decreases as follows. Let \mathrm{last}(d,i) be the last day before day d (including d) on which a contest of type i was held. If contests of type i have never been held yet, we define \mathrm{last}(d,i)=0. At the end of day d, the satisfaction decreases by \sum _{i=1}^{26}c_i \times (d-\mathrm{last}(d,i)).

Please schedule contests on behalf of AtCoder.
If the satisfaction at the end of day D is S, you will get a score of \max(10^6 + S, 0).
There are 50 test cases, and the score of a submission is the total scores for each test case.
You can make submissions multiple times, and the highest score among your submissions will be your score.

Constraints

D = 365

Each c_i is an integer satisfying 0\leq c_i \leq 100.

Each s_{d,i} is an integer satisfying 0\leq s_{d,i} \leq 20000.

Input

Input is given from Standard Input in the following format:

D
c_1 c_2 \cdots c_{26}
s_{1,1} s_{1,2} \cdots s_{1,26}
\vdots
s_{D,1} s_{D,2} \cdots s_{D,26}

Output

Let t_d (1\leq t_d \leq 26) be the type of the contest that will be held at day d.
Print D integers t_d to Standard Output in the following format:

t_1
t_2
\vdots
t_D

Any output that does not follow the above format may result in 0 pointsWA for that test case.

Input Generation

Each integer c_i and s_{d,i} is generated independently and uniformly at random from the integers in the range described in the problem statement.

Sample Input 1

5
86 90 69 51 2 96 71 47 88 34 45 46 89 34 31 38 97 84 41 80 14 4 50 83 7 82
19771 12979 18912 10432 10544 12928 13403 3047 10527 9740 8100 92 2856 14730 1396 15905 6534 4650 11469 3628 8433 2994 10899 16396 18355 11424
6674 17707 13855 16407 12232 2886 11908 1705 5000 1537 10440 10711 4917 10770 17272 15364 19277 18094 3929 3705 7169 6159 18683 15410 9092 4570
6878 4239 19925 1799 375 9563 3445 5658 19857 11401 6997 6498 19933 3848 2426 2146 19745 16880 17773 18359 3921 14172 16730 11157 5439 256
8633 15862 15303 10749 18499 7792 10317 5901 9395 11433 3514 3959 5202 19850 19469 9790 5653 784 18500 10552 17975 16615 7852 197 8471 7452
19855 17918 7990 10572 4333 438 9140 9104 12622 4985 12319 4028 19922 12132 16259 17476 2976 547 19195 19830 16285 4806 4471 9457 2864 2192

Sample Output 1

1
17
13
14
13

Note that this example is a small one for checking the problem specification. It does not satisfy the constraint D=365 and is never actually given as a test case. The final satisfaction with this output is 79325, so the score is 1079325.

Input generator, score calculator, and visualizer

Beginner's Guide

If you don't know what to do, proceed to problem B or C.