(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
;;;
;;; Arithmetic operations with static modulus
;;;

;; FIXME: Currently MOD* and MOD+ doesn't apply MOD when the number of
;; parameters is one.
(defmacro define-mod-operations (divisor)
  `(progn
     (defun mod* (&rest args)
       (reduce (lambda (x y) (mod (* x y) ,divisor)) args))

     (defun mod+ (&rest args)
       (reduce (lambda (x y) (mod (+ x y) ,divisor)) args))

     #+sbcl
     (eval-when (:compile-toplevel :load-toplevel :execute)
       (locally (declare (muffle-conditions warning))
         (sb-c:define-source-transform mod* (&rest args)
           (if (null args)
               1
               (reduce (lambda (x y) `(mod (* ,x ,y) ,',divisor)) args)))
         (sb-c:define-source-transform mod+ (&rest args)
           (if (null args)
               0
               (reduce (lambda (x y) `(mod (+ ,x ,y) ,',divisor)) args)))))

     (define-modify-macro incfmod (delta)
       (lambda (x y) (mod (+ x y) ,divisor)))

     (define-modify-macro decfmod (delta)
       (lambda (x y) (mod (- x y) ,divisor)))

     (define-modify-macro mulfmod (multiplier)
       (lambda (x y) (mod (* x y) ,divisor)))))

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

(in-package :cl-user)

(defmacro dbg (&rest forms)
  #+swank
  (if (= (length forms) 1)
      `(format *error-output* "~A => ~A~%" ',(car forms) ,(car forms))
      `(format *error-output* "~A => ~A~%" ',forms `(,,@forms)))
  #-swank (declare (ignore forms)))

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

(define-mod-operations +mod+)

(defun solve (as k)
  (declare ((simple-array int32 (*)) as))
  (let* ((n (length as))
         (n+ 0)
         (n- 0)
         (as+ (make-array n :element-type 'uint31 :initial-element 0))
         (as- (make-array n :element-type 'uint31 :initial-element 0)))
    (dotimes (i n)
      (let ((a (aref as i)))
        (cond ((> a 0)
               (setf (aref as+ n+) a)
               (incf n+))
              ((< a 0)
               (setf (aref as- n-) (- a))
               (incf n-)))))
    (setq as+ (sort as+ #'>)
          as- (sort as- #'>))
    (dbg as+ as-)
    (let ((cumuls+ (make-array (+ n+ 1) :element-type 'uint31 :initial-element 1))
          (cumuls- (make-array (+ n- 1) :element-type 'uint31 :initial-element 1))
          (logcumuls+ (make-array (+ n+ 1) :element-type 'double-float :initial-element 0d0))
          (logcumuls- (make-array (+ n- 1) :element-type 'double-float :initial-element 0d0))
          (as (delete 0 as)))
      (dotimes (i n+)
        (let ((a (aref as+ i)))
          (setf (aref cumuls+ (+ i 1)) (mod* (aref cumuls+ i) a)
                (aref logcumuls+ (+ i 1)) (+ (aref logcumuls+ i) (log (float a 1d0) 1.1d0)))))
      (dotimes (i n-)
        (let ((a (aref as- i)))
          (setf (aref cumuls- (+ i 1)) (mod* (aref cumuls- i) a)
                (aref logcumuls- (+ i 1)) (+ (aref logcumuls- i) (log (float a 1d0) 1.1d0)))))
      (setq as (sort as #'> :key #'abs))
      (let ((res1 0)
            (maxlog most-negative-double-float)
            fail)
        (loop for d- from 0 to k by 2
              for d+ = (- k d-)
              when (and (<= d- n-) (<= d+ n+))
              do (let ((log (+ (aref logcumuls+ d+) (aref logcumuls- d-))))
                   (when (< (abs (- log maxlog)) 1d-8)
                     (setq fail t)
                     (return))
                   (when (> log maxlog)
                     (when (or (> (abs (- log maxlog)) 1d-9)
                               (< (random 1d0) 0.5d0))
                       (setq maxlog log
                             res1 (mod* (aref cumuls+ d+) (aref cumuls- d-)))))))
        res1
        ;; (if fail
        ;;     (let ((minus 0)
        ;;           (res 1))
        ;;       #>as
        ;;       (dotimes (i (length as))
        ;;         (let ((a (aref as i)))
        ;;           (if (> a 0)
        ;;               (mulfmod res a)
        ;;               (if (= i (- k 1))
        ;;                   (if (evenp minus)
        ;;                       (let ((new-pos (position-if #'plusp as :start i)))
        ;;                         (mulfmod res (aref as new-pos)))
        ;;                       (mulfmod res a))
        ;;                   (progn
        ;;                     (mulfmod res a)
        ;;                     (incf minus))))
        ;;           (when (= i (- k 1))
        ;;             (return))))
        ;;       res)
        ;;     res1)
        ))))

(defun main ()
  (let* ((n (read))
         (k (read))
         (as (make-array n :element-type 'int32 :initial-element 0)))
    (dotimes (i n)
      (setf (aref as i) (read-fixnum)))
    (let ((num+ (count-if #'plusp as))
          (num0 (count 0 as))
          (num- (count-if #'minusp as)))
      (dbg num+ num0 num-)
      (println
       (if (loop for d- from 0 to k by 2
                 for d+ = (- k d-)
                 thereis (and (<= d- num-) (<= d+ num+)))
           (solve as k)
           (let ((as (sort as #'< :key #'abs)))
             (reduce #'mod* as :end k :initial-value 1)))))))

#-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)
    #+os-windows (run-program "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)
    #+os-unix (run-program "xsel" () :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 "4 2
1 2 -3 -4
"
    "12
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4 3
-1 -2 -3 -4
"
    "1000000001
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2 1
-1 1000000000
"
    "1000000000
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "10 10
1000000000 100000000 10000000 1000000 100000 10000 1000 100 10 1
"
    "999983200
")))


(let* ((d-read (read))
    (c (make-array 27))
    (s (make-array (list (+ d-read 1) 27)))
    (td 0)
    (ans 0)
    (last (make-array '(27) :initial-element 0)))

    (loop for i from 1 to 26 do
        (setf (aref c i) (read))
    )
    (loop for i from 1 to d-read do
        (loop for j from 1 to 26 do
            (setf (aref s i j) (read))
        )
    )
    (loop for d from 1 to d-read do
        (progn
            (setq td (read))
            (setf (aref last td) d)
            (incf ans (aref s d td))
            (loop for j from 1 to 26 do
                (decf ans (* (aref c j) (- d (aref last j))))
            )
            (format t "~D~%" ans)
        )
    )
)

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

(Please read problem A first. The maximum score you can get by solving this problem B is 1, which will have almost no effect on your ranking.)

Beginner's Guide

Let's first write a program to calculate the score from a pair of input and output. You can know the total score by submitting your solution, or an official program to calculate a score is often provided for local evaluation as in this contest. Nevertheless, writing a score calculator by yourself is still useful to check your understanding of the problem specification. Moreover, the source code of the score calculator can often be reused for solving the problem or debugging your solution. So it is worthwhile to write a score calculator unless it is very complicated.

Problem Statement

You will be given a contest schedule for D days.
For each d=1,2,\ldots,D, calculate the satisfaction at the end of day d.

Input

Input is given from Standard Input in the form of the input of Problem A followed by the output of Problem A.

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}
t_1
t_2
\vdots
t_D

The constraints and generation methods for the input part are the same as those for Problem A.

For each d, t_d is an integer satisfying 1\leq t_d \leq 26, and your program is expected to work correctly for any value that meets the constraints.

Output

Let v_d be the satisfaction at the end of day d.
Print D integers v_d to Standard Output in the following format:

v_1
v_2
\vdots
v_D

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
1
17
13
14
13

Sample Output 1

18398
35037
51140
65837
79325

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.

Next Step

We can build a solution (schedule) for this problem in the order of day 1, day 2, and so on. And for every partial solution we have built, we can calculate the goodness (satisfaction) by using the above score calculator. So we can construct the following algorithm: for each d=1,2,\ldots,D, we select the contest type that maximizes the satisfaction at the end of day d. You may have already encountered this kind of "greedy algorithms" in algorithm contests such as ABC. Greedy algorithms can guarantee the optimality for several problems, but unfortunately, it doesn't ensure optimality for this problem. However, even if it does not ensure optimality, we can still obtain a reasonable solution in many cases. Let's go back to Problem A and implement the greedy algorithm by utilizing the score calculator you just implemented!

Greedy methods can be applied to a variety of problems, are easy to implement, and often run relatively fast compared to other methods. Greedy is often the most powerful method when we need to process huge inputs.
We can further improve the score by changing the greedy selection criteria (evaluation function), keeping multiple candidates instead of focusing on one best partial solution (beam search), or using the output of greedy algorithms as an initial solution of other methods.
For more information, please refer to the editorial that will be published after the contest.

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.


(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx opt
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
(declaim (inline 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 (inline vector-insert))
(defun vector-insert (vector new-element index)
  (let ((n (length vector)))
    (vector-push new-element vector)
    (loop for i from n above index
          do (rotatef (aref vector i) (aref vector (- i 1)))))
  vector)

(declaim (inline vector-delete))
(defun vector-delete (vector index)
  (loop for i from index below (- (length vector) 1)
        do (rotatef (aref vector i) (aref vector (+ i 1))))
  (vector-pop vector)
  vector)

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

(in-package :cl-user)

(defmacro dbg (&rest forms)
  #+swank
  (if (= (length forms) 1)
      `(format *error-output* "~A => ~A~%" ',(car forms) ,(car forms))
      `(format *error-output* "~A => ~A~%" ',forms `(,,@forms)))
  #-swank (declare (ignore forms)))

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

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

(defun make-state-from (d cs ss schedule)
  (declare (uint32 d)
           ((simple-array uint8 (*)) cs schedule)
           ((simple-array uint32 (* *)) ss))
  (let ((history-table (make-array 26 :element-type '(array uint32 (*)))))
    (dotimes (i 26)
      (let ((history (make-array (+ d 2) :element-type 'int16 :fill-pointer 0)))
        (vector-push -1 history)
        (setf (aref history-table i) history)))
    (dotimes (i d)
      (let ((type (aref schedule i)))
        (vector-push i (aref history-table type))))
    (dotimes (i 26)
      (vector-push d (aref history-table 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
                  :score score))))

(defun state-update! (state day new-type)
  (declare #.OPT
           (uint32 day new-type))
  (symbol-macrolet ((score (state-score state))
                    (cs (state-cs state))
                    (ss (state-ss state))
                    (history-table (state-history-table 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))
      (let* ((pos (bisect-left old-history day))
             (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)))
        (vector-delete old-history pos))
      ;; add new type
      (incf score (aref ss day new-type))
      (let* ((pos (bisect-left new-history day))
             (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)))
        (vector-insert new-history day pos))
      (setf (state-score state) score)
      (setf (aref (state-schedule state) day) new-type)
      state)))

(defun main ()
  (declare #.OPT)
  (let* ((d (read-fixnum))
         (cs (make-array 26 :element-type 'uint8 :initial-element 0))
         (ss (make-array (list d 26) :element-type 'uint32 :initial-element 0))
         (schedule (make-array d :element-type 'uint8 :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))))
    (dotimes (i d)
      (setf (aref schedule i) (- (read-fixnum) 1)))
    (let ((state (make-state-from d cs ss schedule))
          (m (read-fixnum)))
      (write-string
       (with-output-to-string (*standard-output* nil :element-type 'base-char)
         (dotimes (_ m)
           (let* ((day (- (read-fixnum) 1))
                  (new-type (- (read-fixnum) 1)))
             (state-update! state day new-type)
             (println (state-score state)))))))))

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

(Please read problem A first. The maximum score you can get by solving this problem C is 1, which will have almost no effect on your ranking.)

Beginner's Guide

"Local search" is a powerful method for finding a high-quality solution.
In this method, instead of constructing a solution from scratch, we try to find a better solution by slightly modifying the already found solution.
If the solution gets better, update it, and if it gets worse, restore it.
By repeating this process, the quality of the solution is gradually improved over time.
The pseudo-code is as follows.

solution = compute an initial solution (by random generation, or by applying other methods such as greedy)
while the remaining time > 0:
slightly modify the solution (randomly)
if the solution gets worse:
restore the solution

For example, in this problem, we can use the following modification: pick the date d and contest type q at random and change the type of contest to be held on day d to q.
The pseudo-code is as follows.

t[1..D] = compute an initial solution (by random generation, or by applying other methods such as greedy)
while the remaining time > 0:
pick d and q at random
old = t[d] # Remember the original value so that we can restore it later
t[d] = q
if the solution gets worse:
t[d] = old

The most important thing when using the local search method is the design of how to modify solutions.

If the amount of modification is too small, we will soon fall into a dead-end (local optimum) and, conversely, if the amount of modification is too large, the probability of finding an improving move becomes extremely small.

In order to increase the number of iterations, it is desirable to be able to quickly calculate the score after applying a modification.

In this problem C, we focus on the second point.
The score after the modification can, of course, be obtained by calculating the score from scratch.
However, by focusing on only the parts that have been modified, it may be possible to quickly compute the difference between the scores before and after the modification.
From another viewpoint, the impossibility of such a fast incremental calculation implies that a small modification to the solution affects a majority of the score calculation.
In such a case, we may need to redesign how to modify solutions, or there is a high possibility that the problem is not suitable for local search.
Let's implement fast incremental score computation.
It's time to demonstrate the skills of algorithms and data structures you have developed in ABC and ARC!

In this kind of contest, where the objective is to find a better solution instead of the optimal one, a bug in a program does not result in a wrong answer, which may delay the discovery of the bug.
For early detection of bugs, it is a good idea to unit test functions you implemented complicated routines.
For example, if you implement fast incremental score calculation, it is a good idea to test that the scores computed by the fast implementation match the scores computed from scratch, as we will do in this problem C.

Problem Statement

You will be given a contest schedule for D days and M queries of schedule modification.
In the i-th query, given integers d_i and q_i, change the type of contest to be held on day d_i to q_i, and then output the final satisfaction at the end of day D on the updated schedule.
Note that we do not revert each query. That is, the i-th query is applied to the new schedule obtained by the (i-1)-th query.

Input

Input is given from Standard Input in the form of the input of Problem A followed by the output of Problem A and the queries.

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}
t_1
t_2
\vdots
t_D
M
d_1 q_1
d_2 q_2
\vdots
d_M q_M

The constraints and generation methods for the input part are the same as those for Problem A.

For each d=1,\ldots,D, t_d is an integer generated independently and uniformly at random from {1,2,\ldots,26}.

The number of queries M is an integer satisfying 1\leq M\leq 10^5.

For each i=1,\ldots,M, d_i is an integer generated independently and uniformly at random from {1,2,\ldots,D}.

For each i=1,\ldots,26, q_i is an integer satisfying 1\leq q_i\leq 26 generated uniformly at random from the 25 values that differ from the type of contest on day d_i.

Output

Let v_i be the final satisfaction at the end of day D on the schedule after applying the i-th query.
Print M integers v_i to Standard Output in the following format:

v_1
v_2
\vdots
v_M

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
1
17
13
14
13
5
1 7
4 11
3 4
5 24
4 19

Sample Output 1

72882
56634
38425
27930
42884

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.

Next Step

Let's go back to Problem A and implement the local search algorithm by utilizing the incremental score calculator you just implemented!
For this problem, the current modification "pick the date d and contest type q at random and change the type of contest to be held on day d to q" is actually not so good. By considering why it is not good, let's improve the modification operation.
One of the most powerful and widely used variant of the local search method is "Simulated Annealing (SA)", which makes it easier to reach a better solution by stochastically accepting worsening moves.
For more information about SA and other local search techniques, please refer to the editorial that will be published after the contest.


(defun calcAns (c s td d-read)
    (declare (optimise (speed 3) (safety 2))
        (type (simple-array (integer) (*)) c)
        (type (simple-array (integer) (* *)) s)
        (type (simple-array (integer) (*)) td))
    (let ((last (make-array 27 :element-type 'uint32))
        (ans 0))
        (loop for d from 1 to d-read do
        (progn
            (incf ans (+ (aref s d (aref td d))))
            (setf (aref last (aref td d)) d)
            (loop for j from 1 to 26 do
                (decf ans (* (aref c j) (- d (aref last j))))
            )
        )
        )
    ans)
)

(let* ((d-read (read))
    (c (make-array 27 :element-type 'uint8))
    (s (make-array (list (+ d-read 1) 27) :element-type 'uint32))
    (td (make-array (+ d-read 1) :element-type 'uint8))
    (m 0)
    (md 0)
    (mq 0))

    (loop for i from 1 to 26 do
        (setf (aref c i) (read))
    )
    (loop for d from 1 to d-read do
        (loop for j from 1 to 26 do
            (setf (aref s d j) (read))
        )
    )
    (loop for d from 1 to d-read do
        (setf (aref td d) (read))
    )

    (setq m (read))
    (loop for i below m do
        (progn
            (setq md (read))
            (setq mq (read))
            (setf (aref td md) mq)

            (format t "~D~%" (calcAns c s td d-read))
        )
    )
)


(let* ((d-read (read))
    (c (make-array 27))
    (s (make-array (list (+ d-read 1) 27)))
    (td (make-array (+ d-read 1)))
    (m 0)
    (md 0)
    (dq 0)
    (ans 0))

    (loop for i from 1 to 26 do
        (setf (aref c i) (read))
    )
    (loop for d from 1 to d-read do
        (loop for j from 1 to 26 do
            (setf (aref s d j) (read))
        )
    )
    (loop for d from 1 to d-read do
        (setf (aref td d) (read))
    )

    (setq m (read))
    (loop for i below m do
        (progn
            (setq md (read))
            (setq mq (read))
            (setf (aref td md) mq)

            (let ((last (make-array '(27) :initial-element 0)))
                (setq ans 0)
                (loop for d from 1 to d-read do
                (progn
                    (incf ans (+ (aref s d (aref td d))))
                    (setf (aref last (aref td d)) d)
                    (loop for j from 1 to 26 do
                        (decf ans (* (aref c j) (- d (aref last j))))
                    )
                )
                )
            )
            (format t "~D~%" ans)
        )
    )
)


(setq a (read))
(setq b (expt a 2))
(print (+ a (expt a 2) (expt a 3)))

Score : 100 points

Problem Statement

Given an integer a as input, print the value a + a^2 + a^3.

Constraints

1 \leq a \leq 10

a is an integer.

Input

Input is given from Standard Input in the following format:

a

Output

Print the value a + a^2 + a^3 as an integer.

Sample Input 1

2

Sample Output 1

14

When a = 2, we have a + a^2 + a^3 = 2 + 2^2 + 2^3 = 2 + 4 + 8 = 14.

Print the answer as an input. Outputs such as 14.0 will be judged as incorrect.

Sample Input 2

10

Sample Output 2

1110


(defun main ()
  (let ((s (read-line))
	(t1 (read-line))
	(ans 0))
    (loop
       :for char1 :across s
       :for char2 :across t1
       :unless (equal char1 char2)
       :do (incf ans))
    ans))

(format t "~a~%" (main))

Score : 200 points

Problem Statement

Given are strings S and T. Consider changing S to T by repeating the operation below. Find the minimum number of operations required to do so.

Operation: Choose one character of S and replace it with a different character.

Constraints

S and T have lengths between 1 and 2\times 10^5 (inclusive).

S and T consists of lowercase English letters.

S and T have equal lengths.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the answer.

Sample Input 1

cupofcoffee
cupofhottea

Sample Output 1

4

We can achieve the objective in four operations, such as the following:

First, replace the sixth character c with h.

Second, replace the eighth character f with t.

Third, replace the ninth character f with t.

Fourth, replace the eleventh character e with a.

Sample Input 2

abcde
bcdea

Sample Output 2

5

Sample Input 3

apple
apple

Sample Output 3

0

No operations may be needed to achieve the objective.


(let ((s (read-line))
      (_t (read-line))
      (ans 0))
  (loop :for c :across s
        :for d :across _t
        :if (char/= c d)
        :do (incf ans))
  (format t "~A~%" ans))


(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
(defmacro xor (form1 form2)
  (let ((f1 (gensym)) (f2 (gensym)))
    `(let ((,f1 ,form1)
           (,f2 ,form2))
       (if ,f1 (not ,f2) ,f2))))

(in-package :cl-user)

(defmacro dbg (&rest forms)
  #+swank
  (if (= (length forms) 1)
      `(format *error-output* "~A => ~A~%" ',(car forms) ,(car forms))
      `(format *error-output* "~A => ~A~%" ',forms `(,,@forms)))
  #-swank (declare (ignore forms)))

(defmacro define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~A" b)) () '(unsigned-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~A" b)) () '(signed-byte ,b))) bits)))
(define-int-types 2 4 7 8 15 16 31 32 62 63 64)

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun test (a1 a2)
  (loop for x from 0 to a1
        for value = (logxor (- a1 x) (+ a2 x))
        do ;; (format t "~10,'0B~%" value)
           (println value)
           ;; (format t "~D ~D: ~8,'0B~%" (- a1 x) (+ a2 x) value)
        ))

(defun solve (a1 a2 rhs &optional (length 40))
  (declare (uint62 a1 a2 rhs))
  (labels ((dfs (pos value1)
             (declare ((integer -1 40) pos)
                      (uint62 value1))
             (dbg pos value1)
             (let* ((k (- a1 value1))
                    (value2 (+ a2 k)))
               (declare (uint62 value2))
               (when (= pos -1)
                 (if (and (> value1 0)
                          (= (logxor value1 value2) rhs))
                     (return-from solve value1)
                     (return-from dfs)))
               (let* ((cut (dpb 0 (byte pos 0) value2))
                      (mask (ldb (byte 64 0) (lognot (- (ash (logand cut (- cut)) 1) 1)))))
                 ;; (format t "~64,'0B~%" value1)
                 ;; (format t "~64,'0B~%" value2)
                 ;; (format t "~64,'0B~%" mask)
                 (unless (= (logand mask (logxor value1 value2))
                            (logand mask rhs))
                   (return-from dfs)))
               ;; 次を1
               (let* ((next-value1 (+ value1 (ash 1 pos))))
                 ;; (dbg next-value1 next-value2)
                 (when (< next-value1 a1)
                   (dfs (- pos 1) next-value1)))
               (dbg value1 value2 k)
               ;; 次を0
               (dfs (- pos 1) value1))))
    (dfs (- length 1) 0)))

(defun main ()
  (let* ((n (read))
         (as (make-array n :element-type 'uint62 :initial-element 0)))
    (dotimes (i n)
      (setf (aref as i) (read)))
    (let ((a1 (aref as 0))
          (a2 (aref as 1))
          (d (reduce #'logxor as :start 2 :initial-value 0)))
      (dbg a1 a2 d)
      (let ((res (solve a1 a2 d 41)))
        (println
         (if res
             (- a1 res)
             -1))))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
5 3
"
    "1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
3 5
"
    "-1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
1 1 2
"
    "-1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "8
10 9 8 7 6 5 4 3
"
    "3
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
4294967297 8589934593 12884901890
"
    "1
")))

Score : 600 points

Problem Statement

There are N piles of stones. The i-th pile has A_i stones.

Aoki and Takahashi are about to use them to play the following game:

Starting with Aoki, the two players alternately do the following operation:

Operation: Choose one pile of stones, and remove one or more stones from it.

When a player is unable to do the operation, he loses, and the other player wins.

When the two players play optimally, there are two possibilities in this game: the player who moves first always wins, or the player who moves second always wins, only depending on the initial number of stones in each pile.

In such a situation, Takahashi, the second player to act, is trying to guarantee his win by moving at least zero and at most (A_1 - 1) stones from the 1-st pile to the 2-nd pile before the game begins.

If this is possible, print the minimum number of stones to move to guarantee his victory; otherwise, print -1 instead.

Constraints

2 \leq N \leq 300

1 \leq A_i \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum number of stones to move to guarantee Takahashi's win; otherwise, print -1 instead.

Sample Input 1

2
5 3

Sample Output 1

1

Without moving stones, if Aoki first removes 2 stones from the 1-st pile, Takahashi cannot win in any way.

If Takahashi moves 1 stone from the 1-st pile to the 2-nd before the game begins so that both piles have 4 stones, Takahashi can always win by properly choosing his actions.

Sample Input 2

2
3 5

Sample Output 2

-1

It is not allowed to move stones from the 2-nd pile to the 1-st.

Sample Input 3

3
1 1 2

Sample Output 3

-1

It is not allowed to move all stones from the 1-st pile.

Sample Input 4

8
10 9 8 7 6 5 4 3

Sample Output 4

3

Sample Input 5

3
4294967297 8589934593 12884901890

Sample Output 5

1

Watch out for overflows.


(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
(defmacro xor (form1 form2)
  (let ((f1 (gensym)) (f2 (gensym)))
    `(let ((,f1 ,form1)
           (,f2 ,form2))
       (if ,f1 (not ,f2) ,f2))))

(in-package :cl-user)

(defmacro dbg (&rest forms)
  #+swank
  (if (= (length forms) 1)
      `(format *error-output* "~A => ~A~%" ',(car forms) ,(car forms))
      `(format *error-output* "~A => ~A~%" ',forms `(,,@forms)))
  #-swank (declare (ignore forms)))

(defmacro define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~A" b)) () '(unsigned-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~A" b)) () '(signed-byte ,b))) bits)))
(define-int-types 2 4 7 8 15 16 31 32 62 63 64)

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun test (a1 a2)
  (loop for x from 0 to a1
        for value = (logxor (- a1 x) (+ a2 x))
        do ;; (format t "~10,'0B~%" value)
           (println value)
           ;; (format t "~D ~D: ~8,'0B~%" (- a1 x) (+ a2 x) value)
        ))

(defun solve (a1 a2 rhs &optional (length 40))
  (declare #.OPT
           (uint62 a1 a2 rhs))
  (labels ((dfs (pos value1)
             (declare ((integer -1 40) pos)
                      (uint62 value1))
             (let* ((k (- a1 value1))
                    (value2 (+ a2 k)))
               (declare (uint62 value2))
               (when (= pos -1)
                 (if (and (> value1 0)
                          (= (logxor value1 value2) rhs))
                     (return-from solve value1)
                     (return-from dfs)))
               (if (logbitp (+ pos 25) rhs)
                   (unless (xor (logbitp (+ pos 25) value1)
                                (logbitp (+ pos 25) value2))
                     (return-from dfs))
                   (when (xor (logbitp (+ pos 25) value1)
                              (logbitp (+ pos 25) value2))
                     (return-from dfs)))
               ;; 次を1
               (let* ((next-value1 (+ value1 (ash 1 pos))))
                 ;; (dbg next-value1 next-value2)
                 (when (< next-value1 a1)
                   (dfs (- pos 1) next-value1)))
               (dbg value1 value2 k)
               ;; 次を0
               (dfs (- pos 1) value1))))
    (dfs (- length 1) 0)))

(defun main ()
  (let* ((n (read))
         (as (make-array n :element-type 'uint62 :initial-element 0)))
    (dotimes (i n)
      (setf (aref as i) (read)))
    (let ((a1 (aref as 0))
          (a2 (aref as 1))
          (d (reduce #'logxor as :start 2 :initial-value 0)))
      (dbg a1 a2 d)
      (let ((res (solve a1 a2 d 40)))
        (println
         (if res
             (- a1 res)
             -1))))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
5 3
"
    "1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
3 5
"
    "-1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
1 1 2
"
    "-1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "8
10 9 8 7 6 5 4 3
"
    "3
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
4294967297 8589934593 12884901890
"
    "1
")))


(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
(defmacro xor (form1 form2)
  (let ((f1 (gensym)) (f2 (gensym)))
    `(let ((,f1 ,form1)
           (,f2 ,form2))
       (if ,f1 (not ,f2) ,f2))))

(in-package :cl-user)

(defmacro dbg (&rest forms)
  #+swank
  (if (= (length forms) 1)
      `(format *error-output* "~A => ~A~%" ',(car forms) ,(car forms))
      `(format *error-output* "~A => ~A~%" ',forms `(,,@forms)))
  #-swank (declare (ignore forms)))

(defmacro define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~A" b)) () '(unsigned-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~A" b)) () '(signed-byte ,b))) bits)))
(define-int-types 2 4 7 8 15 16 31 32 62 63 64)

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun test (a1 a2)
  (loop for x from 0 to a1
        for value = (logxor (- a1 x) (+ a2 x))
        do ;; (format t "~10,'0B~%" value)
           (println value)
           ;; (format t "~D ~D: ~8,'0B~%" (- a1 x) (+ a2 x) value)
        ))

(defun solve (a1 a2 rhs &optional (length 40))
  (declare #.OPT
           (uint62 a1 a2 rhs))
  (labels ((dfs (pos value1)
             (declare ((integer -1 50) pos)
                      (uint62 value1))
             (let* ((k (- a1 value1))
                    (value2 (+ a2 k)))
               (when (= pos -1)
                 (if (and (> value1 0)
                          (= (logxor value1 value2) rhs))
                     (return-from solve value1)
                     (return-from dfs)))
               (if (logbitp (+ pos 25) rhs)
                   (unless (xor (logbitp (+ pos 25) value1)
                                (logbitp (+ pos 25) value2))
                     (return-from dfs))
                   (when (xor (logbitp (+ pos 25) value1)
                              (logbitp (+ pos 25) value2))
                     (return-from dfs)))
               ;; 次を1
               (let* ((next-value1 (+ value1 (ash 1 pos))))
                 ;; (dbg next-value1 next-value2)
                 (when (< next-value1 a1)
                   (dfs (- pos 1) next-value1)))
               ;; 次を0
               (dfs (- pos 1) value1))))
    (dfs (- length 1) 0)))

(defun main ()
  (let* ((n (read))
         (as (make-array n :element-type 'uint62 :initial-element 0)))
    (dotimes (i n)
      (setf (aref as i) (read)))
    (let ((a1 (aref as 0))
          (a2 (aref as 1))
          (d (reduce #'logxor as :start 2 :initial-value 0)))
      (dbg a1 a2 d)
      (let ((res (solve a1 a2 d 41)))
        (println
         (if res
             (- a1 res)
             -1))))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
5 3
"
    "1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
3 5
"
    "-1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
1 1 2
"
    "-1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "8
10 9 8 7 6 5 4 3
"
    "3
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
4294967297 8589934593 12884901890
"
    "1
")))


(princ (if (upper-case-p (read-char) ) "A" "a"))

Score : 100 points

Problem Statement

An uppercase or lowercase English letter \alpha will be given as input.
If \alpha is uppercase, print A; if it is lowercase, print a.

Constraints

\alpha is an uppercase (A - Z) or lowercase (a - z) English letter.

Input

Input is given from Standard Input in the following format:

α

Output

If \alpha is uppercase, print A; if it is lowercase, print a.

Sample Input 1

B

Sample Output 1

A

B is uppercase, so we should print A.

Sample Input 2

a

Sample Output 2

a

a is lowercase, so we should print a.


(defun app ()
    (let* ((a (string (read-char)))
        (num (char-code (coerce a 'character))))

    (if (> 97 num)
    (princ (string-downcase a))
    (princ (string-upcase a))
    )
    )
)
(app )


(defun main ()
  (let ((n (read))
        (k (read))
        (ans 0)
        p)
    (dotimes (i n)
      (push (read) p))
    (setf p (sort p #'<))
    (dotimes (i k)
      (setf ans (+ ans (pop p))))
    ans))

(format t "~a~%" (main))

Score : 200 points

Problem Statement

A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)

Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.

Constraints

1 \leq K \leq N \leq 1000

1 \leq p_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
p_1 p_2 \ldots p_N

Output

Print an integer representing the minimum possible total price of fruits.

Sample Input 1

5 3
50 100 80 120 80

Sample Output 1

210

This shop sells Fruit 1, 2, 3, 4, and 5 for 50 yen, 100 yen, 80 yen, 120 yen, and 80 yen, respectively.

The minimum total price for three kinds of fruits is 50 + 80 + 80 = 210 yen when choosing Fruit 1, 3, and 5.

Sample Input 2

1 1
1000

Sample Output 2

1000


(let* ((n (read))
    (a (make-array 100001 :initial-element 0))
    (q 0)
    (ans 0))
    (dotimes (i n)
        (let ((d (read)))
        (incf (aref a i))
        (incf ans d)
        )
    )
    (setq q (read))
    (dotimes (i q)
        (let ((b (read))
            (c (read)))
            (incf (aref a c) (aref a b))
            (incf ans (* (aref a b) (- c b)))
            (setf (aref a b) 0)
        )
        (format t "~D~%" ans)
    )
)

Score : 400 points

Problem Statement

You have a sequence A composed of N positive integers: A_{1}, A_{2}, \cdots, A_{N}.

You will now successively do the following Q operations:

In the i-th operation, you replace every element whose value is B_{i} with C_{i}.

For each i (1 \leq i \leq Q), find S_{i}: the sum of all elements in A just after the i-th operation.

Constraints

All values in input are integers.

1 \leq N, Q, A_{i}, B_{i}, C_{i} \leq 10^{5}

B_{i} \neq C_{i}

Input

Input is given from Standard Input in the following format:

N
A_{1} A_{2} \cdots A_{N}
Q
B_{1} C_{1}
B_{2} C_{2}
\vdots
B_{Q} C_{Q}

Output

Print Q integers S_{i} to Standard Output in the following format:

S_{1}
S_{2}
\vdots
S_{Q}

Note that S_{i} may not fit into a 32-bit integer.

Sample Input 1

4
1 2 3 4
3
1 2
3 4
2 4

Sample Output 1

11
12
16

Initially, the sequence A is 1,2,3,4.

After each operation, it becomes the following:

2, 2, 3, 4

2, 2, 4, 4

4, 4, 4, 4

Sample Input 2

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

Sample Output 2

8
4
4

Note that the sequence A may not contain an element whose value is B_{i}.

Sample Input 3

2
1 2
3
1 100
2 100
100 1000

Sample Output 3

102
200
2000


(let* ((n (read))
       (a (make-array '(100001) :initial-element 0))
       (s 0)
       (q 0))
  ;; read
  (loop :for _ :from 1 :to n
        :do (let ((i (read)))
              (incf s i)
              (incf (aref a i))))
  (setf q (read))
  ;;
  (loop :for i :from 1 :to q
        :do (let ((b (read))
                  (c (read)))
              (incf (aref a c) (aref a b))
              (incf s (* (aref a b) (- c b)))
              (format t "~A~%" s)
              (setf (aref a b) 0))))


Score : 200 points

Problem Statement

There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.

Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.

Constraints

1 \leq X \leq 100

1 \leq Y \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

If there is a combination of numbers of cranes and turtles in which the statement is correct, print Yes; otherwise, print No.

Sample Input 1

3 8

Sample Output 1

Yes

The statement "there are 3 animals in total in the garden, and they have 8 legs in total" is correct if there are two cranes and one turtle. Thus, there is a combination of numbers of cranes and turtles in which the statement is correct.

Sample Input 2

2 100

Sample Output 2

No

There is no combination of numbers of cranes and turtles in which this statement is correct.

Sample Input 3

1 2

Sample Output 3

Yes

We also consider the case in which there are only cranes or only turtles.


(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* ((x (read))
         (y (read)))
    (loop for crane from 0 to x
          for turtle = (- x crane)
          when (= (+ (* 2 crane) (* 4 turtle)) y)
          do (write-line "Yes")
             (return-from main))
    (write-line "No")))

#-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 "3 8
"
    "Yes
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2 100
"
    "No
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "1 2
"
    "Yes
")))


(defun split-and-parse-integer (string)
  (loop for i = 0 then (1+ j)
    as j = (position #\Space string :start i)
    collect (parse-integer (subseq string i j))
    while j))
(defparameter x (read))
(defparameter n (read))
(if (not (= n 0))
(defparameter lst (split-and-parse-integer (read-line)))
(defparameter lst nil)
 )
(defparameter ans x)
(defparameter tmp 100)

(loop for i below 100
     do (if (and lst (not (find i lst)) (> tmp (abs (- x i))))
            (progn (setf ans i)
            (setf tmp (abs (- x i))) )
            )
      )

(princ ans)

Score : 300 points

Problem Statement

Given are an integer X and an integer sequence of length N: p_1, \ldots, p_N.

Among the integers not contained in the sequence p_1, \ldots, p_N (not necessarily positive), find the integer nearest to X, that is, find the integer whose absolute difference with X is the minimum. If there are multiple such integers, report the smallest such integer.

Constraints

1 \leq X \leq 100

0 \leq N \leq 100

1 \leq p_i \leq 100

p_1, \ldots, p_N are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X N
p_1 ... p_N

Output

Print the answer.

Sample Input 1

6 5
4 7 10 6 5

Sample Output 1

8

Among the integers not contained in the sequence 4, 7, 10, 6, 5, the one nearest to 6 is 8.

Sample Input 2

10 5
4 7 10 6 5

Sample Output 2

9

Among the integers not contained in the sequence 4, 7, 10, 6, 5, the ones nearest to 10 are 9 and 11. We should print the smaller one, 9.

Sample Input 3

100 0

Sample Output 3

100

When N = 0, the second line in the input will be empty. Also, as seen here, X itself can be the answer.


(defun main(x n)
    (let ((a (make-array n :initial-element 0))
        (b 0)
        (ans T))

        (if (= n 0)
            (setq b x))

        (dotimes (i n)
            (setf (aref a i) (read))
        )

        (dotimes (i n)
            (if (= x (aref a i))
                (setf ans Nil))
        )
        (if (not (eq ans Nil))
            (setq b x)
            (setf ans T)
        )

        (if (= b 0)
            (loop named main-loop for i from 1 to 101
                do (progn
                (if (and (< 0 (- x i)) (eq ans T))
                    (progn
                    (setq b (- x i))
                    (dotimes (j n)
                        (if (= (- x i) (aref a j))
                            (setf ans Nil)))
                    (if (equal ans T)
                        (return-from main-loop)
                        (setf ans T))
                    )
                )
                )
                (if (and (> 101 (+ x i)) (eq ans T))
                    (progn
                    (setq b (+ x i))
                    (dotimes (j n)
                        (if (= (+ x i) (aref a j))
                            (setf ans Nil)))
                    (if (equal ans T)
                        (return-from main-loop)
                    (setf ans T))
                    )
                )

            )
        )
    b)

)
(format t "~D~%" (main (read) (read)))


(defun main ()
  (let ((x (read))
        (n (read))
        (p)
        (ans))
    (dotimes (i n)
      (push (read) p))
    (setf ans (do ((i x (1- i))
                   (j x (1+ j)))
                  ((or (not (member i p)) (not (member j p))) (list i j))))
    (if (member (first ans) p)
        (second ans)
        (first ans))))

(format t "~a~%" (main))


(defun split-and-parse-integer (string)
  (loop for i = 0 then (1+ j)
    as j = (position #\Space string :start i)
    collect (parse-integer (subseq string i j))
    while j))
(defparameter x (read))
(defparameter n (read))
(defparameter lst (split-and-parse-integer (read-line)))
(defparameter ans 1)
(defparameter tmp 100)

(loop for i below 100
     do (if (and (not (find i lst)) (> tmp (abs (- x i))))
            (progn (setf ans i)
            (setf tmp (abs (- x i))) )
            )
      )

(princ ans)


(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
;;;
;;; Queue with singly linked list
;;;

(defstruct (queue (:constructor make-queue
                      (&optional list &aux (tail (last list)))))
  (list nil :type list)
  (tail nil :type list))

(declaim (inline enqueue))
(defun enqueue (obj queue)
  "Pushes OBJ to the end of QUEUE."
  (symbol-macrolet ((list (queue-list queue))
                    (tail (queue-tail queue)))
    (if (null list)
        (setf tail (list obj)
              list tail)
        (setf (cdr tail) (list obj)
              tail (cdr tail))))
  queue)

(declaim (inline dequeue))
(defun dequeue (queue)
  "Removes and returns the element at the front of QUEUE. Returns NIL if QUEUE
is empty."
  (pop (queue-list queue)))

(declaim (inline queue-empty-p))
(defun queue-empty-p (queue)
  (null (queue-list queue)))

(declaim (inline queue-peek))
(defun queue-peek (queue)
  (car (queue-list queue)))

(declaim (inline enqueue-front))
(defun enqueue-front (obj queue)
  "Pushes OBJ to the front of QUEUE."
  (symbol-macrolet ((list (queue-list queue))
                    (tail (queue-tail queue)))
    (if (null list)
        (setf tail (list obj)
              list tail)
        (push obj list))
    queue))

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

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

(defconstant +inf+ #xffffffff)

(defun main ()
  (declare #.OPT)
  (let* ((h (read))
         (w (read))
         (k (read))
         (start-x (- (read) 1))
         (start-y (- (read) 1))
         (goal-x (- (read) 1))
         (goal-y (- (read) 1))
         (plan (make-array (list h w) :element-type 'bit :initial-element 0))
         ;; 既に〇〇進んだ
         (marked (make-array (list h w 4) :element-type 'int32 :initial-element -1))
         (dists (make-array (list h w) :element-type 'uint32 :initial-element +inf+))
         ;; x . y
         (que (make-queue)))
    (declare (uint31 h w k))
    (dotimes (i h)
      (dotimes (j w (read-schar))
        (ecase (read-schar)
          (#\@ (setf (aref plan i j) 1))
          (#\.))))
    (enqueue (cons start-x start-y) que)
    ;; up:0, down:1, left:2, right:3
    (setf (aref dists start-x start-y) 0)
    (setf (aref marked start-x start-y 0) k
          (aref marked start-x start-y 1) k
          (aref marked start-x start-y 2) k
          (aref marked start-x start-y 3) k)
    (loop until (queue-empty-p que)
          for (x . y) of-type (uint31 . uint31) = (dequeue que)
          for dist = (aref dists x y)
          do ;; up
             ;; #>marked
             (setf (aref marked x y 0) k
                   (aref marked x y 1) k
                   (aref marked x y 2) k
                   (aref marked x y 3) k)
             (loop for delta from 1 to k
                   for new-x = (- x delta)
                   while (and (>= new-x 0)
                              ;; あとk-deltaだけ進めるが、既にそれ以上に進んでいたら打ち切れる
                              (>= (- k delta) (aref marked new-x y 0))
                              (zerop (aref plan new-x y)))
                   do (setf (aref marked new-x y 0) (- k delta))
                   when (< (+ dist 1) (aref dists new-x y))
                   do (setf (aref dists new-x y) (+ dist 1))
                      (enqueue (cons new-x y) que))
             ;; down
             (loop for delta from 1 to k
                   for new-x = (+ x delta)
                   while (and (< new-x h)
                              (>= (- k delta) (aref marked new-x y 1))
                              (zerop (aref plan new-x y)))
                   do (setf (aref marked new-x y 1) (- k delta))
                   when (< (+ dist 1) (aref dists new-x y))
                   do (setf (aref dists new-x y) (+ dist 1))
                      (enqueue (cons new-x y) que))
             ;; left
             (loop for delta from 1 to k
                   for new-y = (- y delta)
                   while (and (>= new-y 0)
                              (>= (- k delta) (aref marked x new-y 2))
                              (zerop (aref plan x new-y)))
                   do (setf (aref marked x new-y 2) (- k delta))
                   when (< (+ dist 1) (aref dists x new-y))
                   do (setf (aref dists x new-y) (+ dist 1))
                      (enqueue (cons x new-y) que))
             ;; right
             (loop for delta from 1 to k
                   for new-y = (+ y delta)
                   while (and (< new-y w)
                              (>= (- k delta) (aref marked x new-y 3))
                              (zerop (aref plan x new-y)))
                   do (setf (aref marked x new-y 3) (- k delta))
                   when (< (+ dist 1) (aref dists x new-y))
                   do (setf (aref dists x new-y) (+ dist 1))
                      (enqueue (cons x new-y) que)))
    (let ((res (aref dists goal-x goal-y)))
      (println
       (if (= res +inf+)
           -1
           res)))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3 5 2
3 2 3 4
.....
.@..@
..@..
"
    "5
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "1 6 4
1 1 1 6
......
"
    "2
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3 3 1
2 1 2 3
.@.
.@.
.@.
"
    "-1
")))

Score : 600 points

Problem Statement

Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with H east-west rows and W north-south columns. Let (i,j) be the square at the i-th row from the north and j-th column from the west.

Some of the squares have a lotus leaf on it and cannot be entered.
The square (i,j) has a lotus leaf on it if c_{ij} is @, and it does not if c_{ij} is ..

In one stroke, Snuke can move between 1 and K squares (inclusive) toward one of the four directions: north, east, south, and west.
The move may not pass through a square with a lotus leaf. Moving to such a square or out of the pond is also forbidden.

Find the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2).
If the travel from (x_1,y_1) to (x_2,y_2) is impossible, point out that fact.

Constraints

1 \leq H,W,K \leq 10^6

H \times W \leq 10^6

1 \leq x_1,x_2 \leq H

1 \leq y_1,y_2 \leq W

x_1 \neq x_2 or y_1 \neq y_2.

c_{i,j} is . or @.

c_{x_1,y_1} = .

c_{x_2,y_2} = .

All numbers in input are integers.

Input

Input is given from Standard Input in the following format:

H W K
x_1 y_1 x_2 y_2
c_{1,1}c_{1,2} .. c_{1,W}
c_{2,1}c_{2,2} .. c_{2,W}
:
c_{H,1}c_{H,2} .. c_{H,W}

Output

Print the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2), or print -1 if the travel is impossible.

Sample Input 1

3 5 2
3 2 3 4
.....
.@..@
..@..

Sample Output 1

5

Initially, Snuke is at the square (3,2).
He can reach the square (3, 4) by making five strokes as follows:

From (3, 2), go west one square to (3, 1).

From (3, 1), go north two squares to (1, 1).

From (1, 1), go east two squares to (1, 3).

From (1, 3), go east one square to (1, 4).

From (1, 4), go south two squares to (3, 4).

Sample Input 2

1 6 4
1 1 1 6
......

Sample Output 2

2

Sample Input 3

3 3 1
2 1 2 3
.@.
.@.
.@.

Sample Output 3

-1


(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
;;;
;;; Queue with singly linked list
;;;

(defstruct (queue (:constructor make-queue
                      (&optional list &aux (tail (last list)))))
  (list nil :type list)
  (tail nil :type list))

(declaim (inline enqueue))
(defun enqueue (obj queue)
  "Pushes OBJ to the end of QUEUE."
  (symbol-macrolet ((list (queue-list queue))
                    (tail (queue-tail queue)))
    (if (null list)
        (setf tail (list obj)
              list tail)
        (setf (cdr tail) (list obj)
              tail (cdr tail))))
  queue)

(declaim (inline dequeue))
(defun dequeue (queue)
  "Removes and returns the element at the front of QUEUE. Returns NIL if QUEUE
is empty."
  (pop (queue-list queue)))

(declaim (inline queue-empty-p))
(defun queue-empty-p (queue)
  (null (queue-list queue)))

(declaim (inline queue-peek))
(defun queue-peek (queue)
  (car (queue-list queue)))

(declaim (inline enqueue-front))
(defun enqueue-front (obj queue)
  "Pushes OBJ to the front of QUEUE."
  (symbol-macrolet ((list (queue-list queue))
                    (tail (queue-tail queue)))
    (if (null list)
        (setf tail (list obj)
              list tail)
        (push obj list))
    queue))

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

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

(defconstant +inf+ #xffffffff)

(defun main ()
  (declare #.OPT)
  (let* ((h (read))
         (w (read))
         (k (read))
         (start-x (- (read) 1))
         (start-y (- (read) 1))
         (goal-x (- (read) 1))
         (goal-y (- (read) 1))
         (plan (make-array (list h w) :element-type 'bit :initial-element 0))
         ;; 既に〇〇進んだ
         (marked (make-array (list h w 4) :element-type 'int32 :initial-element -1))
         (dists (make-array (list h w) :element-type 'uint32 :initial-element +inf+))
         ;; x . y
         (que (make-queue)))
    (declare (uint31 h w k))
    (dotimes (i h)
      (dotimes (j w (read-schar))
        (ecase (read-schar)
          (#\@ (setf (aref plan i j) 1))
          (#\.))))
    (enqueue (cons start-x start-y) que)
    ;; up:0, down:1, left:2, right:3
    (setf (aref dists start-x start-y) 0)
    (setf (aref marked start-x start-y 0) k
          (aref marked start-x start-y 1) k
          (aref marked start-x start-y 2) k
          (aref marked start-x start-y 3) k)
    (loop until (queue-empty-p que)
          for (x . y) of-type (uint31 . uint31) = (dequeue que)
          for dist = (aref dists x y)
          do ;; up
             ;; #>marked
             (setf (aref marked x y 0) k
                   (aref marked x y 1) k
                   (aref marked x y 2) k
                   (aref marked x y 3) k)
             (loop for delta from 1 to k
                   for new-x = (- x delta)
                   while (and (>= new-x 0)
                              ;; あとk-deltaだけ進めるが、既にそれ以上に進んでいたら打ち切れる
                              (> (- k delta) (aref marked new-x y 0))
                              (zerop (aref plan new-x y)))
                   do (setf (aref marked new-x y 0) (- k delta))
                   when (< (+ dist 1) (aref dists new-x y))
                   do (setf (aref dists new-x y) (+ dist 1))
                      (enqueue (cons new-x y) que))
             ;; down
             (loop for delta from 1 to k
                   for new-x = (+ x delta)
                   while (and (< new-x h)
                              (> (- k delta) (aref marked new-x y 1))
                              (zerop (aref plan new-x y)))
                   do (setf (aref marked new-x y 1) (- k delta))
                   when (< (+ dist 1) (aref dists new-x y))
                   do (setf (aref dists new-x y) (+ dist 1))
                      (enqueue (cons new-x y) que))
             ;; left
             (loop for delta from 1 to k
                   for new-y = (- y delta)
                   while (and (>= new-y 0)
                              (> (- k delta) (aref marked x new-y 2))
                              (zerop (aref plan x new-y)))
                   do (setf (aref marked x new-y 2) (- k delta))
                   when (< (+ dist 1) (aref dists x new-y))
                   do (setf (aref dists x new-y) (+ dist 1))
                      (enqueue (cons x new-y) que))
             ;; right
             (loop for delta from 1 to k
                   for new-y = (+ y delta)
                   while (and (< new-y w)
                              (> (- k delta) (aref marked x new-y 3))
                              (zerop (aref plan x new-y)))
                   do (setf (aref marked x new-y 3) (- k delta))
                   when (< (+ dist 1) (aref dists x new-y))
                   do (setf (aref dists x new-y) (+ dist 1))
                      (enqueue (cons x new-y) que)))
    (let ((res (aref dists goal-x goal-y)))
      (println
       (if (= res +inf+)
           -1
           res)))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3 5 2
3 2 3 4
.....
.@..@
..@..
"
    "5
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "1 6 4
1 1 1 6
......
"
    "2
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3 3 1
2 1 2 3
.@.
.@.
.@.
"
    "-1
")))


Score : 100 points

Problem Statement

When you asked some guy in your class his name, he called himself S, where S is a string of length between 3 and 20 (inclusive) consisting of lowercase English letters.
You have decided to choose some three consecutive characters from S and make it his nickname. Print a string that is a valid nickname for him.

Constraints

3 \leq |S| \leq 20

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print your answer.

Sample Input 1

takahashi

Sample Output 1

tak

Sample Input 2

naohiro

Sample Output 2

nao


(defun main ()
  (let ((s (read-line)))
    (format t "~a~%" (subseq s 0 3))))

(main)


(defun Lamps (n k)
    (let* ((readLamps (make-array n ))
        (dousyutuLamps (make-array `(,(1+ n)) :initial-element 0))
        (stop t)
        )

        (dotimes (i n)
            (setf (aref readLamps i) (read)))

    (loop named main-loop
          for _ below k
          do (progn
            (loop for i below n
                do (let ((l (max 0 (- i (aref readLamps i))))
                    (r (min (- n 1) (+ i (aref readLamps i)))))
                    (incf (aref dousyutuLamps l))
                    (if (<= (1+ r) n)
                        (decf (aref dousyutuLamps (1+ r)))
                    )
                )
            )
            (loop for i from 1 to n
                do (incf (aref dousyutuLamps i) (aref dousyutuLamps (- i 1)))
            )
            (loop for i below n
                do (progn
                (setf stop (and stop (= (aref dousyutuLamps i) n)))
                (setf (aref readLamps i) (aref dousyutuLamps i))
                (setf (aref dousyutuLamps i) 0)
                )
            )

            (if stop
                (return-from main-loop))
        )
    )
        (loop for i below (- n 1)
            do(format t "~A "(aref readLamps i))
        )
        (format t "~A~%" (aref readLamps (- n 1))))

)
(Lamps (read) (read))

Score : 500 points

Problem Statement

We have N bulbs arranged on a number line, numbered 1 to N from left to right.
Bulb i is at coordinate i.

Each bulb has a non-negative integer parameter called intensity.
When there is a bulb of intensity d at coordinate x, the bulb illuminates the segment from coordinate x-d-0.5 to x+d+0.5.
Initially, the intensity of Bulb i is A_i. We will now do the following operation K times in a row:

For each integer i between 1 and N (inclusive), let B_i be the number of bulbs illuminating coordinate i. Then, change the intensity of each bulb i to B_i.

Find the intensity of each bulb after the K operations.

Constraints

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

1 \leq K \leq 2 \times 10^5

0 \leq A_i \leq N

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \ldots A_N

Output

Print the intensity A{'}_i of each bulb i after the K operations to Standard Output in the following format:

A{'}_1 A{'}_2 \ldots A{'}_N

Sample Input 1

5 1
1 0 0 1 0

Sample Output 1

1 2 2 1 2

Initially, only Bulb 1 illuminates coordinate 1, so the intensity of Bulb 1 becomes 1 after the operation.
Similarly, the bulbs initially illuminating coordinate 2 are Bulb 1 and 2, so the intensity of Bulb 2 becomes 2.

Sample Input 2

5 2
1 0 0 1 0

Sample Output 2

3 3 4 4 3


(defun Lamps (n k)
    (let* ((readLamps (make-array n ))
        (dousyutuLamps (make-array (+ n 1) :initial-element 0))
        (ans "")
        (stop t)
        )

        (dotimes (i n)
            (setf (aref readLamps i) (read)))

    (loop :named main-loop
          :for _ :from 1 :to k
          :do (progn
            (dotimes (j n)
                (let ((l (max 0 (- j (aref readLamps j))))
                    (r (min (- n 1) (+ j (aref readLamps j)))))
                    (incf (aref dousyutuLamps l))
                    (if (<= (+ 1 r) n)
                        (decf (aref dousyutuLamps (+ 1 r)))
                    )
                )
            )
            (loop for j from 1 to n
                do (incf (aref dousyutuLamps j) (aref dousyutuLamps (- j 1)))
            )
            (dotimes (j n)
                (setf stop (and stop (= (aref dousyutuLamps j) n)))
                (setf (aref readLamps j) (aref dousyutuLamps j))
                (setf (aref dousyutuLamps j) 0)
            )

            (if stop
                (return-from main-loop)
                )
        )
    )

        (dotimes (j n)
            (setf ans (concatenate 'string ans (write-to-string (aref readLamps j)))   )
            (if (< j n)
                (setf ans (concatenate 'string ans " "))
            )
        )
    ans)

)
(format t "~A~%" (Lamps (read) (read)))


(defun main ()
  (let* ((n (read))
         (k (read))
         (b (make-array `(,(1+ n)) :initial-element 0))
         (a (make-array `(,(1+ n)) :initial-element 0))
         (stop t))
    (when (<= (1- n) k)
      (loop :for i :from 1 :to (1- n)
            :do (format t "~A " n))
      (format t "~A~%" n)
      (return-from main))
    ;; read
    (loop :for i :from 1 :to n
          :do (setf (aref a i) (read)))
    ;;
    (loop :named main-loop
          :for _ :from 1 :to k
          :do (progn
                (loop :for x :from 1 :to n
                      :do (let ((d (aref a x)))
                            (loop :for i :from (max 1 (- x d)) :to (min n (+ x d))
                                  :do (incf (aref b i)))))
                (loop :for i :from 1 :to n
                      :do (setf stop (and stop (= (aref a i) (aref b i))))
                      :do (setf (aref a i) (aref b i))
                      :do (setf (aref b i) 0))
                (if stop
                    (return-from main-loop)
                    (setf stop t))))
    ;;
    (when (> n 1)
      (loop :for i :from 1 :to (1- n)
            :do (format t "~A " (aref a i))))
    (format t "~A~%" (aref a n))))
(main)