#|
------------------------------------
                Utils
------------------------------------
|#

(in-package :cl-user)

(defconstant +mod+ 1000000007)
;(defconstant +mod+ 998244353)

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam)))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

#-swank
(unless (member :child-sbcl *features*)
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "128MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))

(defmacro define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~a" b)) () '(signed-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~a" b)) () '(unsigned-byte ,b))) bits)))

(define-int-types 2 4 8 16 32 64)

(defmacro buffered-read-line (&optional (buffer-size 30) (in '*standard-input*) (term-char #\Space))
  (let ((buffer (gensym))
        (character (gensym))
        (idx (gensym)))
    `(let* ((,buffer (load-time-value (make-string ,buffer-size :element-type 'base-char))))
       (declare (simple-base-string ,buffer)
                (inline read-byte))
       (loop for ,character of-type base-char =
                ,(if (member :swank *features*)
                     `(read-char ,in nil #\Newline) ; on SLIME
                     `(code-char (read-byte ,in nil #.(char-code #\Newline))))
             for ,idx from 0
             until (char= ,character #\Newline)
             do (setf (schar ,buffer ,idx) ,character)
             finally (when (< ,idx ,buffer-size)
                       (setf (schar ,buffer ,idx) ,term-char))
                     (return (values ,buffer ,idx))))))

(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (declare (inline read-byte)
           #-swank (sb-kernel:ansi-stream in))
  (macrolet ((%read-byte ()
               `(the (unsigned-byte 8)
                     #+swank (char-code (read-char in nil #\Nul))
                     #-swank (read-byte in nil 0))))
    (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) (the (integer 0 #.(floor most-positive-fixnum 10)) (* result 10))))
              (return (if minus (- result) result))))))))

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

(defmacro safe-sort (list test &key (key #'identity))
  `(progn
    (declaim (inline sort sb-impl::stable-sort-list))
    (sort (copy-seq ,list) ,test :key ,key)))

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

(defmacro read-numbers-to-array (size)
  (let ((i (gensym))
        (arr (gensym)))
    `(let ((,arr (make-array ,size
                             :element-type 'fixnum)))
       (declare ((array fixnum 1) ,arr))
       (loop for ,i of-type fixnum below ,size do
            (setf (aref ,arr ,i) (read))
          finally
            (return ,arr)))))

(defmacro read-characters-to-board (row-size column-size)
  (let ((board (gensym))
        (r (gensym))
        (c (gensym))
        (tmp (gensym)))
    `(let ((,board (make-array '(,row-size ,column-size) :element-type 'character :adjustable nil)))
       (dotimes (,r ,row-size ,board)
         (let ((,tmp (buffered-read-line)))
           (dotimes (,c ,column-size)
             (setf (aref ,board ,r ,c) (char ,tmp ,c))))))))

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

(defmethod princ-for-each-line ((sequence vector))
  (loop for i below (length sequence) do
       (princ (aref sequence i))
       (fresh-line)))

(declaim (inline unwrap))
(defun unwrap (list)
  (the string
       (format nil "~{~a~^ ~}" list)))

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

(defmacro maxf (place cand)
  `(setf ,place (max ,place ,cand)))

(defmacro minf (place cand)
  `(setf ,place (min ,place ,cand)))

(defmacro modf (place &optional (m +mod+))
  `(setf ,place (mod ,place ,m)))

(defmacro alambda (parms &body body)
  `(labels ((self ,parms ,@body))
     #'self))

(defun iota (count &optional (start 0) (step 1))
  (loop for i from 0 below count collect (+ start (* i step))))

(defun int->lst (integer)
  (declare ((integer 0) integer))
  (labels ((sub (int &optional (acc nil))
             (declare ((integer 0) int)
                      (list acc))
             (if (zerop int)
                 acc
                 (sub (floor int 10) (cons (rem int 10) acc)))))
    (sub integer)))

(defun lst->int (list)
  (declare (list list))
  (labels ((sub (xs &optional (acc 0))
             (declare (ftype (function (list &optional (integer 0)) (integer 0)) sub))
             (declare (list xs)
                      ((integer 0) acc))
             (if (null xs)
                 acc
                 (sub (rest xs) (+ (* acc 10)
                                   (rem (first xs) 10))))))
    (the fixnum
         (sub list))))

(defun int->str (integer)
  (format nil "~a" integer))

(defun str->int (str)
  (parse-integer str))

(defun char->int (char)
  (declare (character char))
  (- (char-code char) #.(char-code #\0)))

(declaim (inline prime-factorize-to-list))
(defun prime-factorize-to-list (integer)
  (declare ((integer 0) integer))
  (the list
       (if (<= integer 1)
           nil
           (loop
              while (<= (* f f) integer)
              with acc list = nil
              with f integer = 2
              do
                (if (zerop (rem integer f))
                    (progn
                      (push f acc)
                      (setq integer (floor integer f)))
                    (incf f))
              finally
                (when (/= integer 1)
                  (push integer acc))
                (return (reverse acc))))))

(declaim (inline prime-p))
(defun prime-p (integer)
  (declare ((integer 1) integer))
  (if (= integer 1)
      nil
      (loop
         with f = 2
         while (<= (* f f) integer)
         do
           (when (zerop (rem integer f))
             (return nil))
           (incf f)
         finally
           (return t))))

#|
------------------------------------
                Body
------------------------------------
|#

(defun main ()
  (declare #.OPT)
  (let ((n (read))
        (q (read)))
    (declare (uint32 n q))
    (let ((edges (make-array n :element-type 'list :adjustable nil :initial-element nil))
          (res (make-array n :element-type 'fixnum :adjustable nil :initial-element 0)))
      (declare ((array list 1) edges)
               ((array fixnum 1) res))
      (loop repeat (1- n) do
           (let ((a (1- (read-fixnum)))
                 (b (1- (read-fixnum))))
             (declare (uint32 a b))
             (push a (aref edges b))
             (push b (aref edges a))))
      (loop repeat q do
           (let ((p (1- (read-fixnum)))
                 (x (read-fixnum)))
             (declare (uint32 p x))
             (incf (aref res p) x)))
      (labels ((recursive-incf (node parent)
                 (declare (uint32 q)
                          (integer parent))
                 (unless (= parent -1)
                   (incf (aref res node)
                         (aref res parent)))
                 (mapc (lambda (child)
                         (unless (= child parent)
                           (recursive-incf child node)))
                       (aref edges node))))
        (recursive-incf 0 -1)
        (princ (unwrap (map 'list #'identity res)))
        (fresh-line)))))

#-swank (main)

Score : 400 points

Problem Statement

Given is a rooted tree with N vertices numbered 1 to N.
The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.

Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.

Now, the following Q operations will be performed:

Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.

Find the value of the counter on each vertex after all operations.

Constraints

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

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

1 \leq a_i < b_i \leq N

1 \leq p_j \leq N

1 \leq x_j \leq 10^4

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q

Output

Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between.

Sample Input 1

4 3
1 2
2 3
2 4
2 10
1 100
3 1

Sample Output 1

100 110 111 110

The tree in this input is as follows:

Each operation changes the values of the counters on the vertices as follows:

Operation 1: Increment by 10 the counter on every vertex contained in the subtree rooted at Vertex 2, that is, Vertex 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 0, 10, 10, 10, respectively.

Operation 2: Increment by 100 the counter on every vertex contained in the subtree rooted at Vertex 1, that is, Vertex 1, 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 110, 110, respectively.

Operation 3: Increment by 1 the counter on every vertex contained in the subtree rooted at Vertex 3, that is, Vertex 3. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 111, 110, respectively.

Sample Input 2

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

Sample Output 2

20 20 20 20 20 20


#|
------------------------------------
                Utils
------------------------------------
|#

(in-package :cl-user)

(defconstant +mod+ 1000000007)
;(defconstant +mod+ 998244353)

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam)))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

#-swank
(unless (member :child-sbcl *features*)
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "128MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))

(defmacro define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~a" b)) () '(signed-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~a" b)) () '(unsigned-byte ,b))) bits)))

(define-int-types 2 4 8 16 32 64)

(defmacro buffered-read-line (&optional (buffer-size 30) (in '*standard-input*) (term-char #\Space))
  (let ((buffer (gensym))
        (character (gensym))
        (idx (gensym)))
    `(let* ((,buffer (load-time-value (make-string ,buffer-size :element-type 'base-char))))
       (declare (simple-base-string ,buffer)
                (inline read-byte))
       (loop for ,character of-type base-char =
                ,(if (member :swank *features*)
                     `(read-char ,in nil #\Newline) ; on SLIME
                     `(code-char (read-byte ,in nil #.(char-code #\Newline))))
             for ,idx from 0
             until (char= ,character #\Newline)
             do (setf (schar ,buffer ,idx) ,character)
             finally (when (< ,idx ,buffer-size)
                       (setf (schar ,buffer ,idx) ,term-char))
                     (return (values ,buffer ,idx))))))

(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (declare (inline read-byte)
           #-swank (sb-kernel:ansi-stream in))
  (macrolet ((%read-byte ()
               `(the (unsigned-byte 8)
                     #+swank (char-code (read-char in nil #\Nul))
                     #-swank (read-byte in nil 0))))
    (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) (the (integer 0 #.(floor most-positive-fixnum 10)) (* result 10))))
              (return (if minus (- result) result))))))))

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

(defmacro safe-sort (list test &key (key #'identity))
  `(progn
    (declaim (inline sort sb-impl::stable-sort-list))
    (sort (copy-seq ,list) ,test :key ,key)))

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

(defmacro read-numbers-to-array (size)
  (let ((i (gensym))
        (arr (gensym)))
    `(let ((,arr (make-array ,size
                             :element-type 'fixnum)))
       (declare ((array fixnum 1) ,arr))
       (loop for ,i of-type fixnum below ,size do
            (setf (aref ,arr ,i) (read))
          finally
            (return ,arr)))))

(defmacro read-characters-to-board (row-size column-size)
  (let ((board (gensym))
        (r (gensym))
        (c (gensym))
        (tmp (gensym)))
    `(let ((,board (make-array '(,row-size ,column-size) :element-type 'character :adjustable nil)))
       (dotimes (,r ,row-size ,board)
         (let ((,tmp (buffered-read-line)))
           (dotimes (,c ,column-size)
             (setf (aref ,board ,r ,c) (char ,tmp ,c))))))))

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

(defmethod princ-for-each-line ((sequence vector))
  (loop for i below (length sequence) do
       (princ (aref sequence i))
       (fresh-line)))

(declaim (inline unwrap))
(defun unwrap (list)
  (the string
       (format nil "~{~a~^ ~}" list)))

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

(defmacro maxf (place cand)
  `(setf ,place (max ,place ,cand)))

(defmacro minf (place cand)
  `(setf ,place (min ,place ,cand)))

(defmacro modf (place &optional (m +mod+))
  `(setf ,place (mod ,place ,m)))

(defmacro alambda (parms &body body)
  `(labels ((self ,parms ,@body))
     #'self))

(defun iota (count &optional (start 0) (step 1))
  (loop for i from 0 below count collect (+ start (* i step))))

(defun int->lst (integer)
  (declare ((integer 0) integer))
  (labels ((sub (int &optional (acc nil))
             (declare ((integer 0) int)
                      (list acc))
             (if (zerop int)
                 acc
                 (sub (floor int 10) (cons (rem int 10) acc)))))
    (sub integer)))

(defun lst->int (list)
  (declare (list list))
  (labels ((sub (xs &optional (acc 0))
             (declare (ftype (function (list &optional (integer 0)) (integer 0)) sub))
             (declare (list xs)
                      ((integer 0) acc))
             (if (null xs)
                 acc
                 (sub (rest xs) (+ (* acc 10)
                                   (rem (first xs) 10))))))
    (the fixnum
         (sub list))))

(defun int->str (integer)
  (format nil "~a" integer))

(defun str->int (str)
  (parse-integer str))

(defun char->int (char)
  (declare (character char))
  (- (char-code char) #.(char-code #\0)))

(declaim (inline prime-factorize-to-list))
(defun prime-factorize-to-list (integer)
  (declare ((integer 0) integer))
  (the list
       (if (<= integer 1)
           nil
           (loop
              while (<= (* f f) integer)
              with acc list = nil
              with f integer = 2
              do
                (if (zerop (rem integer f))
                    (progn
                      (push f acc)
                      (setq integer (floor integer f)))
                    (incf f))
              finally
                (when (/= integer 1)
                  (push integer acc))
                (return (reverse acc))))))

(declaim (inline prime-p))
(defun prime-p (integer)
  (declare ((integer 1) integer))
  (if (= integer 1)
      nil
      (loop
         with f = 2
         while (<= (* f f) integer)
         do
           (when (zerop (rem integer f))
             (return nil))
           (incf f)
         finally
           (return t))))

#|
------------------------------------
                Body
------------------------------------
|#

(defun main ()
  (declare #.OPT)
  (let ((n (read))
        (q (read)))
    (declare (uint32 n q))
    (let ((edges (make-array n :element-type t :initial-element nil))
          (res (make-array n :element-type 'fixnum :initial-element 0)))
      (declare ((array t 1) edges)
               ((array fixnum 1) res))
      (loop repeat (1- n) do
           (let ((a (1- (read)))
                 (b (1- (read))))
             (declare (uint32 a b))
             (push a (aref edges b))
             (push b (aref edges a))))
      (loop repeat q do
           (let ((p (1- (read)))
                 (x (read)))
             (declare (uint32 p x))
             (incf (aref res p) x)))
      (labels ((recursive-incf (node parent)
                 (declare (uint32 q)
                          (integer parent))
                 (unless (= parent -1)
                   (incf (aref res node)
                         (aref res parent)))
                 (mapc (lambda (child)
                         (unless (= child parent)
                           (recursive-incf child node)))
                       (aref edges node))))
        (recursive-incf 0 -1)
        (princ (unwrap (map 'list #'identity res)))
        (fresh-line)))))

#-swank (main)

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

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.


#|
------------------------------------
                Utils
------------------------------------
|#

(in-package :cl-user)

(defconstant +mod+ 1000000007)
;(defconstant +mod+ 998244353)

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam)))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

#-swank
(unless (member :child-sbcl *features*)
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "128MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))

(defmacro define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~a" b)) () '(signed-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~a" b)) () '(unsigned-byte ,b))) bits)))

(define-int-types 2 4 8 16 32 64)

(defmacro buffered-read-line (&optional (buffer-size 30) (in '*standard-input*) (term-char #\Space))
  (let ((buffer (gensym))
        (character (gensym))
        (idx (gensym)))
    `(let* ((,buffer (load-time-value (make-string ,buffer-size :element-type 'base-char))))
       (declare (simple-base-string ,buffer)
                (inline read-byte))
       (loop for ,character of-type base-char =
                ,(if (member :swank *features*)
                     `(read-char ,in nil #\Newline) ; on SLIME
                     `(code-char (read-byte ,in nil #.(char-code #\Newline))))
             for ,idx from 0
             until (char= ,character #\Newline)
             do (setf (schar ,buffer ,idx) ,character)
             finally (when (< ,idx ,buffer-size)
                       (setf (schar ,buffer ,idx) ,term-char))
                     (return (values ,buffer ,idx))))))

(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (declare (inline read-byte)
           #-swank (sb-kernel:ansi-stream in))
  (macrolet ((%read-byte ()
               `(the (unsigned-byte 8)
                     #+swank (char-code (read-char in nil #\Nul))
                     #-swank (read-byte in nil 0))))
    (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) (the (integer 0 #.(floor most-positive-fixnum 10)) (* result 10))))
              (return (if minus (- result) result))))))))

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

(defmacro safe-sort (list test &key (key #'identity))
  `(progn
    (declaim (inline sort sb-impl::stable-sort-list))
    (sort (copy-seq ,list) ,test :key ,key)))

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

(defmacro read-numbers-to-array (size)
  (let ((i (gensym))
        (arr (gensym)))
    `(let ((,arr (make-array ,size
                             :element-type 'fixnum)))
       (declare ((array fixnum 1) ,arr))
       (loop for ,i of-type fixnum below ,size do
            (setf (aref ,arr ,i) (read))
          finally
            (return ,arr)))))

(defmacro read-characters-to-board (row-size column-size)
  (let ((board (gensym))
        (r (gensym))
        (c (gensym))
        (tmp (gensym)))
    `(let ((,board (make-array '(,row-size ,column-size) :element-type 'character :adjustable nil)))
       (dotimes (,r ,row-size ,board)
         (let ((,tmp (buffered-read-line)))
           (dotimes (,c ,column-size)
             (setf (aref ,board ,r ,c) (char ,tmp ,c))))))))

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

(defmethod princ-for-each-line ((sequence vector))
  (loop for i below (length sequence) do
       (princ (aref sequence i))
       (fresh-line)))

(declaim (inline unwrap))
(defun unwrap (list)
  (the string
       (format nil "~{~a~^ ~}" list)))

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

(defmacro maxf (place cand)
  `(setf ,place (max ,place ,cand)))

(defmacro minf (place cand)
  `(setf ,place (min ,place ,cand)))

(defmacro modf (place &optional (m +mod+))
  `(setf ,place (mod ,place ,m)))

(defmacro alambda (parms &body body)
  `(labels ((self ,parms ,@body))
     #'self))

(defun iota (count &optional (start 0) (step 1))
  (loop for i from 0 below count collect (+ start (* i step))))

(defun int->lst (integer)
  (declare ((integer 0) integer))
  (labels ((sub (int &optional (acc nil))
             (declare ((integer 0) int)
                      (list acc))
             (if (zerop int)
                 acc
                 (sub (floor int 10) (cons (rem int 10) acc)))))
    (sub integer)))

(defun lst->int (list)
  (declare (list list))
  (labels ((sub (xs &optional (acc 0))
             (declare (ftype (function (list &optional (integer 0)) (integer 0)) sub))
             (declare (list xs)
                      ((integer 0) acc))
             (if (null xs)
                 acc
                 (sub (rest xs) (+ (* acc 10)
                                   (rem (first xs) 10))))))
    (the fixnum
         (sub list))))

(defun int->str (integer)
  (format nil "~a" integer))

(defun str->int (str)
  (parse-integer str))

(defun char->int (char)
  (declare (character char))
  (- (char-code char) #.(char-code #\0)))

(declaim (inline prime-factorize-to-list))
(defun prime-factorize-to-list (integer)
  (declare ((integer 0) integer))
  (the list
       (if (<= integer 1)
           nil
           (loop
              while (<= (* f f) integer)
              with acc list = nil
              with f integer = 2
              do
                (if (zerop (rem integer f))
                    (progn
                      (push f acc)
                      (setq integer (floor integer f)))
                    (incf f))
              finally
                (when (/= integer 1)
                  (push integer acc))
                (return (reverse acc))))))

(declaim (inline prime-p))
(defun prime-p (integer)
  (declare ((integer 1) integer))
  (if (= integer 1)
      nil
      (loop
         with f = 2
         while (<= (* f f) integer)
         do
           (when (zerop (rem integer f))
             (return nil))
           (incf f)
         finally
           (return t))))

#|
------------------------------------
                Body
------------------------------------
|#

(defun main ()
  (declare #.OPT)
  (let ((n (read))
        (q (read)))
    (let ((edges (make-array n :initial-element nil))
          (res (make-array n :initial-element 0)))
      (loop repeat (1- n) do
           (let ((a (1- (read)))
                 (b (1- (read))))
             (push a (aref edges b))
             (push b (aref edges a))))
      (loop repeat q do
           (let ((p (1- (read)))
                 (x (read)))
             (incf (aref res p) x)))
      (labels ((recursive-incf (node parent)
                 (unless (= parent -1)
                   (incf (aref res node)
                         (aref res parent)))
                 (mapc (lambda (child)
                         (unless (= child parent)
                           (recursive-incf child node)))
                       (aref edges node))))
        (recursive-incf 0 -1)
        (princ (unwrap (map 'list #'identity res)))
        (fresh-line)))))

#-swank (main)


#|
------------------------------------
                Utils
------------------------------------
|#

(in-package :cl-user)

(defconstant +mod+ 1000000007)
;(defconstant +mod+ 998244353)

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam)))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

#-swank
(unless (member :child-sbcl *features*)
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "128MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))

(defmacro define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~a" b)) () '(signed-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~a" b)) () '(unsigned-byte ,b))) bits)))

(define-int-types 2 4 8 16 32 64)

(defmacro buffered-read-line (&optional (buffer-size 30) (in '*standard-input*) (term-char #\Space))
  (let ((buffer (gensym))
        (character (gensym))
        (idx (gensym)))
    `(let* ((,buffer (load-time-value (make-string ,buffer-size :element-type 'base-char))))
       (declare (simple-base-string ,buffer)
                (inline read-byte))
       (loop for ,character of-type base-char =
                ,(if (member :swank *features*)
                     `(read-char ,in nil #\Newline) ; on SLIME
                     `(code-char (read-byte ,in nil #.(char-code #\Newline))))
             for ,idx from 0
             until (char= ,character #\Newline)
             do (setf (schar ,buffer ,idx) ,character)
             finally (when (< ,idx ,buffer-size)
                       (setf (schar ,buffer ,idx) ,term-char))
                     (return (values ,buffer ,idx))))))

(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (declare (inline read-byte)
           #-swank (sb-kernel:ansi-stream in))
  (macrolet ((%read-byte ()
               `(the (unsigned-byte 8)
                     #+swank (char-code (read-char in nil #\Nul))
                     #-swank (read-byte in nil 0))))
    (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) (the (integer 0 #.(floor most-positive-fixnum 10)) (* result 10))))
              (return (if minus (- result) result))))))))

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

(defmacro safe-sort (list test &key (key #'identity))
  `(progn
    (declaim (inline sort sb-impl::stable-sort-list))
    (sort (copy-seq ,list) ,test :key ,key)))

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

(defmacro read-numbers-to-array (size)
  (let ((i (gensym))
        (arr (gensym)))
    `(let ((,arr (make-array ,size
                             :element-type 'fixnum)))
       (declare ((array fixnum 1) ,arr))
       (loop for ,i of-type fixnum below ,size do
            (setf (aref ,arr ,i) (read))
          finally
            (return ,arr)))))

(defmacro read-characters-to-board (row-size column-size)
  (let ((board (gensym))
        (r (gensym))
        (c (gensym))
        (tmp (gensym)))
    `(let ((,board (make-array '(,row-size ,column-size) :element-type 'character :adjustable nil)))
       (dotimes (,r ,row-size ,board)
         (let ((,tmp (buffered-read-line)))
           (dotimes (,c ,column-size)
             (setf (aref ,board ,r ,c) (char ,tmp ,c))))))))

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

(defmethod princ-for-each-line ((sequence vector))
  (loop for i below (length sequence) do
       (princ (aref sequence i))
       (fresh-line)))

(declaim (inline unwrap))
(defun unwrap (list)
  (the string
       (format nil "~{~a~^ ~}" list)))

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

(defmacro maxf (place cand)
  `(setf ,place (max ,place ,cand)))

(defmacro minf (place cand)
  `(setf ,place (min ,place ,cand)))

(defmacro modf (place &optional (m +mod+))
  `(setf ,place (mod ,place ,m)))

(defmacro alambda (parms &body body)
  `(labels ((self ,parms ,@body))
     #'self))

(defun iota (count &optional (start 0) (step 1))
  (loop for i from 0 below count collect (+ start (* i step))))

(defun int->lst (integer)
  (declare ((integer 0) integer))
  (labels ((sub (int &optional (acc nil))
             (declare ((integer 0) int)
                      (list acc))
             (if (zerop int)
                 acc
                 (sub (floor int 10) (cons (rem int 10) acc)))))
    (sub integer)))

(defun lst->int (list)
  (declare (list list))
  (labels ((sub (xs &optional (acc 0))
             (declare (ftype (function (list &optional (integer 0)) (integer 0)) sub))
             (declare (list xs)
                      ((integer 0) acc))
             (if (null xs)
                 acc
                 (sub (rest xs) (+ (* acc 10)
                                   (rem (first xs) 10))))))
    (the fixnum
         (sub list))))

(defun int->str (integer)
  (format nil "~a" integer))

(defun str->int (str)
  (parse-integer str))

(defun char->int (char)
  (declare (character char))
  (- (char-code char) #.(char-code #\0)))

(declaim (inline prime-factorize-to-list))
(defun prime-factorize-to-list (integer)
  (declare ((integer 0) integer))
  (the list
       (if (<= integer 1)
           nil
           (loop
              while (<= (* f f) integer)
              with acc list = nil
              with f integer = 2
              do
                (if (zerop (rem integer f))
                    (progn
                      (push f acc)
                      (setq integer (floor integer f)))
                    (incf f))
              finally
                (when (/= integer 1)
                  (push integer acc))
                (return (reverse acc))))))

(declaim (inline prime-p))
(defun prime-p (integer)
  (declare ((integer 1) integer))
  (if (= integer 1)
      nil
      (loop
         with f = 2
         while (<= (* f f) integer)
         do
           (when (zerop (rem integer f))
             (return nil))
           (incf f)
         finally
           (return t))))

#|
------------------------------------
                Body
------------------------------------
|#

(defun solve (n q edges queries)
  (let ((memo (make-array n :initial-element 0))
        (children (make-array n :initial-element nil)))
    (mapc (lambda (query)
            (incf (aref memo (car query))
                  (cdr query)))
          queries)
    (mapc (lambda (edge)
            (let ((a (car edge))
                  (b (cdr edge)))
              (when (> a b)
                (rotatef a b))
              (push b (aref children a))))
          edges)
    (labels ((increment-for-children (node val)
               (when (aref children node)
                 (mapc (lambda (child)
                         (incf (aref memo child) val)
                         (increment-for-children child (aref memo child)))
                       (aref children node)))))
      (increment-for-children 0 (aref memo 0))
      memo)))

(defun main ()
  (declare #.OPT)
  (let ((n (read))
        (q (read)))
    (let ((edges (loop repeat (1- n) collect (cons (1- (read))
                                              (1- (read)))))
          (queries (loop repeat q collect (cons (1- (read))
                                                (read)))))
      (princ (unwrap (coerce (solve n q edges queries) 'list)))
      (fresh-line))))

#-swank (main)


;;;; queue
(defstruct queue
  (entrance nil)
  (exit nil))

(defun enqueue (item queue)
  (let ((cell (list item)))
    (if (queue-entrance queue)
        (setf (cdr (queue-entrance queue)) cell)
        (setf (queue-exit queue) cell))
    (setf (queue-entrance queue) cell)))

(defun dequeue (queue)
  (when (queue-exit queue)
    (prog1 (pop (queue-exit queue))
      (unless (queue-exit queue)
        (setf (queue-entrance queue) nil)))))

;;;; main
(let* ((n (read))
       (q (read))
       (e (make-array (list (1+ n)) :initial-element nil))
       (chk (make-array (list (1+ n)) :initial-element nil))
       (ans (make-array (list (1+ n)) :initial-element 0)))
  (loop :for i :from 1 :to (1- n)
        :for a := (read)
        :for b := (read)
        :do (push b (aref e a))
        :do (push a (aref e b)))
  (loop :for j :from 1 :to q
        :for p := (read)
        :for x := (read)
        :do (incf (aref ans p) x))
  ;
  (let ((q (make-queue)))
    (enqueue 1 q)
    (loop :while (queue-exit q)
          :for x := (dequeue q)
          :do (unless (aref chk x)
                (setf (aref chk x) t)
                (loop :for y :in (aref e x)
                      :do (unless (aref chk y)
                            (incf (aref ans y) (aref ans x))
                            (enqueue y q))))))
  (loop :for i :from 1 :to (1- n)
        :do (format t "~A " (aref ans i)))
  (format t "~A~%" (aref ans n)))


(let* ((n (read))
       (q (read))
       (graph (make-array n :element-type 'list :initial-element nil))
       (qval (make-array n :initial-element 0))
       (ans (make-array n :initial-element 0)))
  (dotimes (i (1- n))
    (let ((a (1- (read)))
          (b (1- (read))))
      (push b (aref graph a))
      (push a (aref graph b))))
  (dotimes (i q)
    (let ((p (1- (read)))
          (x (read)))
      (incf (aref qval p) x)))
  (labels
    ((dfs (x val parent)
       (setf (aref ans x) (+ (aref qval x) val))
       (dolist (child (aref graph x))
         (unless (= child parent)
           (dfs child (aref ans x) x)))))
    (dfs 0 0 -1))
  (dotimes (i n)
    (format t "~A " (aref ans i)))
  (fresh-line))


(defun f (graph a s parent visited)
  (setf (aref visited s) t)
  (setf (aref a s) (+ (aref a s) (aref a parent)))
  (mapc (lambda (x) (unless (aref visited x)
                      (f graph a x s visited)))
        (gethash s graph)))
(let* ((n (read))
       (q (read))
       (a (make-array (1+ n)))
       (graph (make-hash-table)))
  (loop for i from 1 below n
        do (let ((a (read)) (b (read)))
             (setf (gethash a graph) (cons b (gethash a graph)))
             (setf (gethash b graph) (cons a (gethash b graph)))))
  (loop for i below q
        do (let ((p (read)) (x (read)))
             (setf (aref a p) (+ x (aref a p)))))
  (let ((visited (make-array (1+ n) :initial-element nil)))
    (f graph a 1 0 visited))
  (loop for i from 1 to n
        do (format t "~A " (aref a i)))
  (terpri))


#-swank
(unless (member :child-sbcl *features*)
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "128MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))
;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (ql:quickload '(:cl-debug-print :fiveam))
  #-swank (set-dispatch-macro-character #\# #\> (lambda (s c p) (declare (ignore c p)) (read s nil (values) t))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
(declaim (ftype (function * (values (integer 0 #.most-positive-fixnum) &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (declare #.OPT
           #-swank (sb-kernel:ansi-stream in))
  (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* ((result (loop (let ((byte (%read-byte)))
                           (cond ((<= 48 byte 57)
                                  (return (- byte 48)))
                                 ((zerop byte) ; #\Nul
                                  (error "Read EOF or #\Nul.")))))))
      (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 result)))))))

(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
;; Should we do this with UNWIND-PROTECT?
(defmacro with-buffered-stdout (&body body)
  "Buffers all outputs to *STANDARD-OUTPUT* in BODY and flushes them to
*STANDARD-OUTPUT* after BODY has been done (without error). Note that only
BASE-CHAR is allowed."
  (let ((out (gensym)))
    `(let ((,out (make-string-output-stream :element-type 'base-char)))
       (let ((*standard-output* ,out))
         ,@body)
       (write-string (get-output-stream-string ,out)))))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (q (read))
         (graph (make-array n :element-type 'list :initial-element nil))
         (qtable (make-array n :element-type 'uint32 :initial-element 0))
         (res (make-array n :element-type 'uint32 :initial-element 0)))
    (declare (uint31 n q))
    (dotimes (i (- n 1))
      (let ((a (- (read-fixnum) 1))
            (b (- (read-fixnum) 1)))
        (push a (aref graph b))
        (push b (aref graph a))))
    (dotimes (i q)
      (let ((p (- (read-fixnum) 1))
            (x (read-fixnum)))
        (incf (aref qtable p) x)))
    (sb-int:named-let dfs ((v 0) (parent n) (sum 0))
      (declare (uint62 v parent sum))
      (let ((new-sum (the uint62 (+ sum (aref qtable v)))))
        (setf (aref res v) new-sum)
        (dolist (neighbor (aref graph v))
          (unless (= parent (the uint31 neighbor))
            (dfs neighbor v new-sum)))))
    (with-buffered-stdout
      (loop with init = t
            for x across res
            do (if init (setq init nil) (write-char #\ ))
               (princ x)))
    (terpri)))

#-swank (main)


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (ql:quickload '(:cl-debug-print :fiveam))
  #-swank (set-dispatch-macro-character #\# #\> (lambda (s c p) (declare (ignore c p)) (read s nil (values) t))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (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 #\-))
                                  (setf 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))))))))

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (let* ((n (read))
         (m (read))
         (p (read))
         (graph (make-array n :element-type 'list :initial-element nil))
         (revgraph (make-array n :element-type 'list :initial-element nil))
         (dp (make-array n :element-type 'fixnum :initial-element most-positive-fixnum)))
    (declare (uint32 n m p))
    (dotimes (i m)
      (let ((a (- (read-fixnum) 1))
            (b (- (read-fixnum) 1))
            (c (read-fixnum)))
        (push (cons b (- p c)) (aref graph a))
        (push a (aref revgraph b))))
    (setf (aref dp 0) 0)
    (dotimes (_ n)
      (dotimes (v n)
        (unless (= (aref dp v) most-positive-fixnum)
          (dolist (node (aref graph v))
            (let ((dest (car node))
                  (cost (cdr node)))
              (declare (fixnum dest cost))
              (setf (aref dp dest)
                    (min (aref dp dest)
                         (+ (aref dp v) cost))))))))
    (let ((cands (make-hash-table)))
      (dotimes (v n)
        (unless (= (aref dp v) most-positive-fixnum)
          (dolist (node (aref graph v))
            (let ((dest (car node))
                  (cost (cdr node)))
              (declare (fixnum dest cost))
              (when (> (aref dp dest) (+ (aref dp v) cost))
                (setf (gethash dest cands) t))))))
      (let ((visited (make-array n :element-type 'bit :initial-element 0)))
        (sb-int:named-let recur ((v (- n 1)))
          (setf (aref visited v) 1)
          (when (gethash v cands)
            (println -1)
            (return-from main cands))
          (dolist (neighbor (aref revgraph v))
            (when (zerop (aref visited neighbor))
              (recur neighbor)))))
      (println (max 0 (- (aref dp (- n 1))))))))

#-swank (main)

Score : 500 points

Problem Statement

There is a directed graph with N vertices numbered 1 to N and M edges.
The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge.
Additionally, there is a button on Vertex N.

We will play a game on this graph.
You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins.
It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it.
As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.

When you reach Vertex N, you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.)
However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead.

Your score will be the number of coins you have after this payment.
Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.

Constraints

2 \leq N \leq 2500

1 \leq M \leq 5000

1 \leq A_i, B_i \leq N

1 \leq C_i \leq 10^5

0 \leq P \leq 10^5

All values in input are integers.

Vertex N can be reached from Vertex 1.

Input

Input is given from Standard Input in the following format:

N M P
A_1 B_1 C_1
:
A_M B_M C_M

Output

If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1.

Sample Input 1

3 3 10
1 2 20
2 3 30
1 3 45

Sample Output 1

35

There are two ways to travel from Vertex 1 to Vertex 3:

Vertex 1 \rightarrow 2 \rightarrow 3: You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you have 50 - 20 = 30 coins left.

Vertex 1 \rightarrow 2: You collect 45 coins on the way. After one minute from the start of the game, you press the button, pay 1 \times 10 = 10 coins, and you have 45 - 10 = 35 coins left.

Thus, the maximum score that can be obtained is 35.

Sample Input 2

2 2 10
1 2 100
2 2 100

Sample Output 2

-1

The edge extending from Vertex 1 takes you to Vertex 2. If you then traverse the edge extending from Vertex 2 to itself t times and press the button, your score will be 90 + 90t. Thus, you can infinitely increase your score, which means there is no maximum value of the score that can be obtained.

Sample Input 3

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

Sample Output 3

0

There is no way to travel from Vertex 1 to Vertex 4 other than traversing the edge leading from Vertex 1 to Vertex 4 directly. You will pick up one coin along this edge, but after being asked to paying 10 coins, your score will be 0.

Note that you can collect an infinite number of coins if you traverse the edge leading from Vertex 1 to Vertex 2, but this is pointless since you can no longer reach Vertex 4 and end the game.


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (ql:quickload '(:cl-debug-print :fiveam))
  #-swank (set-dispatch-macro-character #\# #\> (lambda (s c p) (declare (ignore c p)) (read s nil (values) t))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (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 #\-))
                                  (setf 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))))))))

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (let* ((n (read))
         (m (read))
         (p (read))
         (graph (make-array n :element-type 'list :initial-element nil))
         (dp (make-array n :element-type 'fixnum :initial-element most-positive-fixnum)))
    (declare (uint32 n m p))
    (dotimes (i m)
      (let ((a (- (read-fixnum) 1))
            (b (- (read-fixnum) 1))
            (c (read-fixnum)))
        (push (cons b (- p c)) (aref graph a))))
    (setf (aref dp 0) 0)
    (dotimes (i n)
      (dotimes (v n)
        (unless (= (aref dp v) most-positive-fixnum)
          (dolist (node (aref graph v))
            (let ((dest (car node))
                  (cost (cdr node)))
              (declare (fixnum dest cost))
              (setf (aref dp dest)
                    (min (aref dp dest)
                         (+ (aref dp v) cost))))))))
    (let ((tmp-res (aref dp (- n 1))))
      (dotimes (i n)
        (dotimes (v n)
          (unless (= (aref dp v) most-positive-fixnum)
            (dolist (node (aref graph v))
              (let ((dest (car node))
                    (cost (cdr node)))
                (declare (fixnum dest cost))
                (setf (aref dp dest)
                      (min (aref dp dest)
                           (+ (aref dp v) cost))))))))
      (if (= tmp-res (aref dp (- n 1)))
          (println (max 0 (- tmp-res)))
          (println -1)))))

#-swank (main)

;; For Test
#+swank
(defun io-equal (in-string out-string &key (target #'main) (test #'equal))
  "Passes IN-STRING to *STANDARD-INPUT*, executes TARGET, 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 target)))))))

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    (run-program "C:/msys64/usr/bin/cat.exe" '("/dev/clipboard") :output out)))

#+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 3 10
1 2 20
2 3 30
1 3 45
"
    "35
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2 2 10
1 2 100
2 2 100
"
    "-1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4 5 10
1 2 1
1 4 1
3 4 1
2 2 100
3 3 100
"
    "0
")))


(let ((n (read))
      (h nil))
  (loop :for i :from 1 :to n
        :do (push (read) h))
  ;
  (loop :named main
        :with p := (car h)
        :for x :in (cdr h)
        :do (cond ((= x (1+ p))
                   (setf p p))
                  ((<= x p)
                   (setf p x))
                  (t
                   (format t "No~%")
                   (return-from main)))
        :finally (format t "Yes~%")))

Score : 300 points

Problem Statement

There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i.

For each square, you will perform either of the following operations once:

Decrease the height of the square by 1.

Do nothing.

Determine if it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq H_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

If it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right, print Yes; otherwise, print No.

Sample Input 1

5
1 2 1 1 3

Sample Output 1

Yes

You can achieve the objective by decreasing the height of only the second square from the left by 1.

Sample Input 2

4
1 3 2 1

Sample Output 2

No

Sample Input 3

5
1 2 3 4 5

Sample Output 3

Yes

Sample Input 4

1
1000000000

Sample Output 4

Yes


#-swank
(unless (member :child-sbcl *features*)
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "128MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))
(defmacro dp (name args memo-size &body body)
  (let ((memo (gensym)))
    `(let ((,memo (make-array ,memo-size :initial-element nil)))
       (defun ,name ,args
         (or (aref ,memo ,@args)
             (setf (aref ,memo ,@args)
                   ,@body))))))

(defun split (x str)
  (let ((pos (search x str))
        (size (length x)))
    (if pos
      (cons (subseq str 0 pos)
            (split x (subseq str (+ pos size))))
      (list str))))

(defun main (line)
  (labels ((f (last lst)
             (when (null lst)
               (return-from f t))
             (when (> last (car lst))
               (return-from f nil))
             (f (max last (1- (car lst))) (cdr lst))))
    (if (f -1000000000 line) "Yes" "No")))

(let* ((n (read))
       (line (loop repeat n collect (read))))
  (princ (main line)))


(let* ((n (read))
       (lst (make-array n :initial-contents (reverse (loop :repeat n :collect (read))))))
  (loop :for k :from 1 :upto (- (length lst) 1)
        :do(if (= (aref lst k) (1+ (aref lst (1- k))))
               (decf (aref lst k))))
  (if (or (= n 1)
          (loop :for k :from 0 :upto (- n 2)
                :always (>= (aref lst k) (aref lst (1+ k)))))
      (princ "Yes")
      (princ "No")))


(defun and-list (function list)
  (if (cdr list)
      (if (funcall function (first list) (second list))
          (and-list function (cdr list))
          nil)
      t))
(let* ((n (read))
       (lst (reverse (loop :repeat n :collect (read)))))
  (loop :for k :from 1 :upto (- (length lst) 1)
        :do(if (= (elt lst k) (1+ (elt lst (1- k))))
               (decf (elt lst k))))
  (if (or (not (cdr lst))
          (and-list #'>= lst))
      (princ "Yes")
      (princ "No")))


(defun solve (n heights)
  (loop with decreasing = nil
        for i from 0 below (1- n)
        for j = (1+ i)
        do (if (< (aref heights j) (aref heights i))
               (if (or (< 1 (- (aref heights i) (aref heights j))) decreasing)
                   (return nil)
                   (setf decreasing t))
               (setf decreasing nil))
        finally (return t)))

#-swank
(let* ((n (read))
       (heights (make-array n :element-type 'fixnum)))
  (loop for i from 0 below n
        do (setf (aref heights i) (read)))
  (format t "~:[No~;Yes~]~%" (solve n heights)))


(defun solve (n heights)
  (loop with decreasing = nil
        for i from 0 below (1- n)
        for j = (1+ i)
        do (if (< (aref heights j) (aref heights i))
               (if decreasing
                   (return nil)
                   (setf decreasing t))
               (setf decreasing nil))
        finally (return t)))

#-swank
(let* ((n (read))
       (heights (make-array n :element-type 'fixnum)))
  (loop for i from 0 below n
        do (setf (aref heights i) (read)))
  (format t "~:[No~;Yes~]~%" (solve n heights)))


(let ((n (read))
      (pre 0)
      (flg T)
      temp)
     (loop repeat n
           do (setf temp (read))
              (cond ((> pre temp) (setf flg nil))
                    ((< pre (1- temp)) (setf pre (1- temp)))))
     (princ (if flg "Yes" "No")))


(defun split (x str)
  (let ((pos (search x str))
        (size (length x)))
    (if pos
      (cons (subseq str 0 pos)
            (split x (subseq str (+ pos size))))
      (list str))))

(defparameter N (read))
(defparameter hs (make-array N :initial-contents
                             (mapcar #'parse-integer
                                     (split " " (read-line)))))

(defun walk (lst)
  (loop for i from (- (length lst) 2) downto 0
        if (<= (aref lst i) (aref lst (1+ i)))
        collect 1 into result
        else if (= (1- (aref lst i)) (aref lst (1+ i)))
        collect (progn (decf (aref lst i) 1) 1) into result
        else collect 0 into result
        finally (return (reduce #'* result))))

(defun answer (lst)
  (if (= 1 (length lst))
      (format t "Yes")
      (if (= 1 (walk lst))
          (format t "Yes")
          (format t "No"))))

(answer hs)


(defun split (x str)
  (let ((pos (search x str))
        (size (length x)))
    (if pos
      (cons (subseq str 0 pos)
            (split x (subseq str (+ pos size))))
      (list str))))

(defparameter N (read))
(defparameter hs (make-array N :initial-contents
                             (mapcar #'parse-integer
                                     (split " " (read-line)))))

(defun compare (s1 s2)
  (let ((diff (- s1 s2)))
       (if (< 1 diff)
           0
           1)))

(defun walk (lst)
  (loop for i from (- (length lst) 2) downto 0
        if (<= (aref lst i) (aref lst (1+ i)))
        collect 1 into result
        else if (= (1- (aref lst i)) (aref lst (1+ i)))
        collect (progn (decf (aref lst i) 1) 1) into result
        else collect 0 into result
        finally (return (reduce #'* result))))

(defun answer (lst)
  (if (= 1 (length lst))
      (format t "Yes")
      (if (= 2 (length lst))
          (if (<= (aref lst 0) (aref lst 1))
              (format t "Yes"))
          (if (= 1 (walk hs))
              (format t "Yes")
              (format t "No")))))

(answer hs)


(defun split (x str)
  (let ((pos (search x str))
        (size (length x)))
    (if pos
      (cons (subseq str 0 pos)
            (split x (subseq str (+ pos size))))
      (list str))))

(defparameter N (read))
(defparameter hs (make-array N :initial-contents
                             (mapcar #'parse-integer
                                     (split " " (read-line)))))

(defun check (s0 s1 s2)
  (if (and (<= (1- s0) s1)
           (<= (1- s0) s2)
           (<= (1- s1) s2))
      1
      0))

(defun walk (lst)
  (loop for i from 1 to (- (length lst) 2)
        collect (check (aref lst (1- i))
                       (aref lst i)
                       (aref lst (1+ i))) into result
        finally (return (reduce #'* result))))

(defun answer (lst)
  (if (= 1 (length lst))
      (format t "Yes")
      (if (= 2 (length lst))
          (if (<= (aref lst 0) (aref lst 1))
              (format t "Yes"))
          (if (= 1 (walk hs))
              (format t "Yes")
              (format t "No")))))

(answer hs)


(defun split (x str)
  (let ((pos (search x str))
        (size (length x)))
    (if pos
      (cons (subseq str 0 pos)
            (split x (subseq str (+ pos size))))
      (list str))))

(defparameter N (read))
(defparameter hs (split " " (read-line)))

(defun check (s0 s1 s2)
  (if (and (<= (1- s0) s1)
           (<= (1- s0) s2)
           (<= (1- s1) s2))
      1
      0))

(defun walk (lst)
  (loop for i from 1 to (- (length lst) 2)
        collect (check (aref lst (1- i))
                       (aref lst i)
                       (aref lst (1+ i))) into result
        finally (return (reduce #'* result))))

(defun answer (lst)
  (if (= 1 (length lst))
      (format t "Yes")
      (if (= 2 (length lst))
          (if (<= (aref lst 0) (aref lst 1))
              (format t "Yes"))
          (if (= 1 (walk hs))
              (format t "Yes")
              (format t "No")))))

(answer hs)
(defparameter N (read))
(defparameter hs (make-array N :initial-contents
                             (mapcar #'digit-char-p
                                     (remove-if #'(lambda (x) (eq x #\ ))
                                                (concatenate 'list (read-line))))))

(defun check (s0 s1 s2)
  (if (and (<= (1- s0) s1)
           (<= (1- s0) s2)
           (<= (1- s1) s2))
      1
      0))

(defun walk (lst)
  (loop for i from 1 to (- (length lst) 2)
        collect (check (aref lst (1- i))
                       (aref lst i)
                       (aref lst (1+ i))) into result
        finally (return (reduce #'* result))))

(defun answer (lst)
  (if (= 1 (length lst))
      (format t "Yes")
      (if (= 2 (length lst))
          (if (<= (aref lst 0) (aref lst 1))
              (format t "Yes"))
          (if (= 1 (walk hs))
              (format t "Yes")
              (format t "No")))))

(answer hs)


(defparameter N (read))
(defparameter hs (make-array N :initial-contents
                             (mapcar #'digit-char-p
                                     (remove-if #'(lambda (x) (eq x #\ ))
                                                (concatenate 'list (read-line))))))

(defun check (s0 s1 s2)
  (if (and (<= (1- s0) s1)
           (<= (1- s0) s2)
           (<= (1- s1) s2))
      1
      0))

(defun walk (lst)
  (loop for i from 1 to (- (length lst) 2)
        collect (check (aref lst (1- i))
                       (aref lst i)
                       (aref lst (1+ i))) into result
        finally (return (reduce #'* result))))

(defun answer (lst)
  (if (= 1 (length lst))
      (format t "Yes")
      (if (= 2 (length lst))
          (if (<= (aref lst 0) (aref lst 1))
              (format t "Yes"))
          (if (= 1 (walk hs))
              (format t "Yes")
              (format t "No")))))

(answer hs)


(defparameter N (read))
(defparameter hs (make-array :initial-contents
                             (mapcar #'digit-char-p
                                     (remove-if #'(lambda (x) (eq x #\ ))
                                                (concatenate 'list (read-line))))))

(defun check (s0 s1 s2)
  (if (and (<= (1- s0) s1)
           (<= (1- s0) s2)
           (<= (1- s1) s2))
      1
      0))

(defun walk (lst)
  (loop for i from 1 to (- (length lst) 2)
        collect (check (aref lst (1- i))
                       (aref lst i)
                       (aref lst (1+ i))) into result
        finally (return(reduce #'* result))))

(defun answer (lst)
  (if (= 1 (length lst))
      (format t "Yes")
      (if (= 2 (length lst))
          (if (<= (aref lst 0) (aref lst 1))
              (format t "Yes"))
          (if (= 1 (walk hs))
              (format t "Yes")
              (format t "No"))))))

(answer hs)
(defparameter N (read))
(defparameter hs (make-array :initial-contents
                             (mapcar #'digit-char-p
                                     (remove-if #'(lambda (x) (eq x #\ ))
                                                (concatenate 'list (read-line)))))

(defun check (s0 s1 s2)
  (if (and (<= (1- s0) s1)
           (<= (1- s0) s2)
           (<= (1- s1) s2))
      1
      0))

(defun walk (lst)
  (loop for i from 1 to (- (length lst) 2)
        collect (check (aref lst (1- i))
                       (aref lst i)
                       (aref lst (1+ i))) into result
        finally (return(reduce #'* result))))

(defun answer (lst)
  (if (= 1 (length lst))
      (format t "Yes")
      (if (= 2 (length lst))
          (if (<= (aref lst 0) (aref lst 1))
              (format t "Yes"))
          (if (= 1 (walk hs))
              (format t "Yes")
              (format t "No"))))))

(answer hs)


(defparameter N (read))
(defparameter hs (make-array :initial-contents
                             (mapcar #'digit-char-p
                                     (remove-if #'(lambda (x) (eq x #\ ))
                                                (concatenate 'list (read-line)))))

(defun check (s0 s1 s2)
  (if (and (<= (1- s0) s1)
           (<= (1- s0) s2)
           (<= (1- s1) s2))
      1
      0))

(defun walk (lst)
  (loop for i from 1 to (- (length lst) 2)
        collect (check (aref lst (1- i))
                       (aref lst i)
                       (aref lst (1+ i))) into result
        finally (return(reduce #'* result))))

(defun answer (lst)
  (if (= 1 (length lst))
      (format t "Yes")
      (if (= 2 (length lst))
          (if (<= (aref lst 0) (aref lst 1))
              (format t "Yes"))
          (if (= 1 (walk hs))
              (format t "Yes")
              (format t "No"))))))

(answer hs)


(defparameter N (read))
(defparameter hs (make-array :initial-contents
                             (mapcar #'digit-char-p
                                     (remove-if #'(lambda (x) (eq x #\ ))
                                                (concatenate 'array (read-line)))))

(defun check (s0 s1 s2)
  (if (and (<= (1- s0) s1)
           (<= (1- s0) s2)
           (<= (1- s1) s2))
      1
      0))

(defun walk (lst)
  (loop for i from 1 to (- (length lst) 2)
        collect (check (aref lst (1- i))
                       (aref lst i)
                       (aref lst (1+ i))) into result
        finally (return(reduce #'* result))))

(defun answer (lst)
  (if (= 1 (length lst))
      (format t "Yes")
      (if (= 2 (length lst))
          (if (<= (aref lst 0) (aref lst 1))
              (format t "Yes"))
          (if (= 1 (walk hs))
              (format t "Yes")
              (format t "No")))))


(defparameter N (read))
(defparameter hs (make-array N))
(loop for i from 0 to (1- N) do
  (setf (aref hs i) (read)))

(defun check (s0 s1 s2)
  (if (and (<= (1- s0) s1)
           (<= (1- s0) s2)
           (<= (1- s1) s2))
      1
      0))

(defun walk (lst)
  (loop for i from 1 to (- (length lst) 2)
        collect (check (aref lst (1- i))
                       (aref lst i)
                       (aref lst (1+ i))) into result
        finally (return(reduce #'* result))))

(defun answer (lst)
  (if (= 1 (length lst))
      (format t "Yes")
      (if (= 2 (length lst))
          (if (<= (aref lst 0) (aref lst 1))
              (format t "Yes"))
          (if (= 1 (walk hs))
              (format t "Yes")
              (format t "No")))))


(defparameter N (read))
(defparameter hs (make-array N))
(loop for i from 0 to (1- N) do
      (setf (aref hs i) (read)))

(defun check (s0 s1 s2)
  (if (and (<= (1- s0) s1)
           (<= (1- s0) s2)
           (<= (1- s1) s2))
      1
      0))

(defun walk (lst)
  (loop for i from 1 to (- (length lst) 2)
        collect (check (aref lst (1- i))
                       (aref lst i)
                       (aref lst (1+ i))) into result
        finally (return (reduce #'* result))))

(defun answer (lst)
  (if (= 1 (length lst))
      (format t "Yes")
      (if (= 2 (length lst))
          (if (<= (aref lst 0) (aref lst 1))
              (format t "Yes"))
          (if (= 1 (walk hs))
                  (format t "Yes")
                  (format t "No")))))


(defparameter N (read))
(defparameter hs (make-array N))
(loop for i from 0 to (1- N) do
      (setf (aref hs i) (read)))

(defun check (s0 s1 s2)
  (if (and (<= (1- s0) s1)
           (<= (1- s0) s2)
           (<= (1- s1) s2))
      1
      0))

(defun walk (lst)
  (loop for i from 1 to (- (length lst) 2)
        collect (check (aref lst (1- i))
                       (aref lst i)
                       (aref lst (1+ i))) into result
        finally (return (reduce #'* result))))

(defun answer (lst)
  (if (= 1 (length lst))
      (format t "Yes")
      (if (= 2 (length lst))
          (if (<= (aref lst 0) (aref lst 1))
              (format t "Yes")
              (if (= 1 (walk hs))
                  (format t "Yes")
                  (format t "No"))))))

(answer hs)


(defparameter N (read))
(defparameter Hs (make-array N))
(loop for i from 0 to (1- N) do
      (setf (aref Hs i) (read)))

(defun check (lst)
  (if (= 1 (length lst))
      (format t "Yes")
      (loop for i from 0 to (- (length lst) 2) do
            (if (< (aref lst i)
                   (aref lst (1+ i)))
                (setf (aref lst (1+ i))
                      (1- (aref lst (1+ i))))
                (if (> (aref lst i)
                       (aref lst (1+ i)))
                    finally (format t "No")))
            finally (format t "Yes"))))

(check Hs)


(defparameter N (read))
(defparameter Hs (make-array N))
(loop for i from 0 to (1- N) do
      (setf (aref Hs i) (read)))

(if (= N 1)
    (format t "Yes")
	(loop for i from 0 to (- N 2) do
          (if (> (- (aref Hs i) (aref Hs (1+ i)))
                 1)
              finally (format t "No")
              (setf (aref Hs (1+ i))
                    (1- (aref Hs (1+ i)))))
          finally (format t "Yes")))


(defparameter N (read))
(defparameter Hs (make-array N))
(loop for i from 0 to (1- N) do
      (setf (aref Hs i) (read)))

(defun check (lst)
  (if (= 1 (length lst))
      (format t "Yes")
      (loop for i from 0 to (- (length lst) 2) do
            (when (> 1 (1- (aref lst i)
                           (aref lst (1+ i))))
              (format t "No"))
            finally (format t "Yes"))))

(check Hs)


(let* ((n (read))
       (lst (reverse (loop :repeat n :collect (read)))))
  (if (cond ((= (length lst) 1) t)
            ((= (length lst) 2) (<= (1- (first lst)) (second lst)))
            (t (not (find t (mapcar #'< lst (cdr lst) (cddr lst))))))
      (princ "Yes")
      (princ "No")))


(defparameter N (read))
(defparameter Hs (make-array N))
(loop for i from 0 to (1- N) do
      (setf (aref Hs i) (read)))

(if (= N 1)
    (format t "Yes")
	(loop for i from 0 to (- N 2) do
          (when (< 1 (- (aref Hs i)
                        (aref Hs (1+ i))))
              (format t "No"))
          finally (format t "Yes")))


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (ql:quickload '(:cl-debug-print :fiveam))
  #-swank (set-dispatch-macro-character #\# #\> (lambda (s c p) (declare (ignore c p)) (read s nil (values) t))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (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 #\-))
                                  (setf 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))))))))

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (let* ((n (read))
         (hs (make-array n :element-type 'uint32)))
    (dotimes (i n) (setf (aref hs i) (read-fixnum)))
    (decf (aref hs 0))
    (loop for i from 1 below n
          do (cond ((< (aref hs (- i 1)) (aref hs i))
                    (decf (aref hs i)))
                   ((= (aref hs (- i 1)) (aref hs i)))
                   (t (write-line "No")
                      (return-from main))))
    #>hs
    (write-line "Yes")))

#-swank (main)

;; For Test
#+swank
(defun io-equal (in-string out-string &optional (func #'main))
  "Passes IN-STRING to *STANDARD-INPUT*, executes FUNC, 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+))))
    (equal (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 func)))))))

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    (run-program "C:/msys64/usr/bin/cat.exe" '("/dev/clipboard") :output out)))

#+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*))
  (let ((*standard-output* out))
    (etypecase thing
      (null ; Runs #'MAIN with the string on clipboard
       (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 ; Runs #'MAIN with the string in a text file
       (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)


(defun solve (L R)
  (if (< 671 (- R L)) 0
      (loop for i from L to (1- R)
            minimize (loop for j from (1+ i) to R
                           minimize (mod (* i j) 2019)))))

(princ (solve (read) (read)))

Score : 300 points

Problem Statement

You are given two non-negative integers L and R.
We will choose two integers i and j such that L \leq i < j \leq R.
Find the minimum possible value of (i \times j) \mbox{ mod } 2019.

Constraints

All values in input are integers.

0 \leq L < R \leq 2 \times 10^9

Input

Input is given from Standard Input in the following format:

L R

Output

Print the minimum possible value of (i \times j) \mbox{ mod } 2019 when i and j are chosen under the given condition.

Sample Input 1

2020 2040

Sample Output 1

2

When (i, j) = (2020, 2021), (i \times j) \mbox{ mod } 2019 = 2.

Sample Input 2

4 5

Sample Output 2

20

We have only one choice: (i, j) = (4, 5).


(defun solve (l r)
  (loop for i from l below r
        minimize
        (loop for j from (1+ i) to r
              for x = (mod (* i j) 2019)
              when (= x 0)
              do (return-from solve 0)
              minimize x)))
(princ (solve (read) (read)))


(defun solve (l r)
  (setf l (mod l 2019))
  (setf r (mod r 2019))
  (if (> l r)
    0
    (* l (1+ l))))
(princ (solve (read) (read)))


(let ((L (read))
      (R (read))
      (arr (make-array 0 :element-type 'integer
                         :adjustable t
                         :fill-pointer 0))
      (ans 10000))
     (loop for i from L upto (min R (+ L 4040))
           do (vector-push-extend (rem i 2019) arr))
     (setf arr (sort arr #'<))
     (loop for i from 0 below (1- (min (1+ (- R L)) 4040))
           do (loop for j from (1+ i) below (min (1+ (- R L)) 4040) while (not (zerop ans))
                    do (setf ans (min ans (rem (* (aref arr i) (aref arr j)) 2019)))))
     (princ ans))


(let ((L (read))
      (R (read))
      (arr (make-array 0 :element-type 'integer
                         :adjustable t
                         :fill-pointer 0)))
     (loop for i from L upto (min R (+ L 2020))
           do (vector-push-extend (rem i 2019) arr))
     (setf arr (sort arr #'<))
     (princ (* (aref arr 0) (aref arr 1))))


(declaim (optimize (speed 3) (debug 0) (safety 0)))
(let* ((n (read))
       (m (read))
       (ans 2019))
  (loop :named p-loop :for p :from n :upto (1- m)
        :do(loop :for q :from (1+ p) :upto m :do(if (= 0 (mod (* p q) 2019))
                                                    (progn (setf ans 0) (return-from p-loop))
                                                    (if (< (mod (* p q) 2019) ans)
                                                        (setf ans (mod (* p q) 2019))) )))
  (princ ans))


(declaim (optimize (speed 3) (debug 0) (safety 0)))
(let* ((n (read))
       (m (read))
       (x (loop :for k :from 1 :thereis(if (> (* k 2019) n) (1- k)))))
  (cond ((= n 0) (princ 0))
    ((= x 0) (princ (loop :for p :from n :upto (1- m) :minimize(loop :for q :from (1+ p) :upto m :minimize (mod (* p q) 2019)))))
        ((<= n (* 2019 x) m) (princ 0))
        (t (princ (loop :for p :from n :upto (1- m) :minimize(loop :for q :from (1+ p) :upto m :minimize (mod (* p q) 2019)))))))


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (ql:quickload '(:cl-debug-print :fiveam))
  #-swank (set-dispatch-macro-character #\# #\> (lambda (s c p) (declare (ignore c p)) (read s nil (values) t))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
(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* ((l (read))
         (r (read))
         (mod-table (make-array 2019 :element-type 'bit :initial-element 0)))
    (when (>= (- r l) 2019)
      (println 0)
      (return-from main))
    (loop for i from l to r
          do (setf (aref mod-table (mod i 2019)) 1))
    (let ((res #xffffffff))
      (dotimes (i 2019)
        (loop for j from (+ i 1) below 2019
              do (when (= 1 (aref mod-table i) (aref mod-table j))
                   (setf res (min res (mod (* i j) 2019))))))
      (println res))))

#-swank(main)

;; For Test
#+swank
(defun io-equal (in-string out-string &optional (func #'main))
  "Passes IN-STRING to *STANDARD-INPUT*, executes FUNC, and returns true if the
string output to *STANDARD-OUTPUT* is equal to OUT-STRING."
  (labels ((ensure-last-lf (s)
             (if (and (> (length s) 0)
                      (eql (char s (- (length s) 1)) #\Linefeed))
                 s
                 (uiop:strcat s uiop:+lf+))))
    (equal (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 func)))))))

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    (run-program "C:/msys64/usr/bin/cat.exe" '("/dev/clipboard") :output out)))

#+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*))
  (let ((*standard-output* out))
    (etypecase thing
      (null ; Runs #'MAIN with the string on clipboard
       (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 ; Runs #'MAIN with the string in a text file
       (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 "2020 2040
"
    "2
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4 5
"
    "20
")))


(defparameter s (read-line))

(defun cut (text)
  (if (equal "BC" (subseq text 0 2))
      (cut (subseq text 2))
      (if (or (equal "C" (subseq text 0 1))
              (equal "B" (subseq text 0 1)))
          (cut (subseq text 1))
          text)))

(let ((counter 0))
     (defun answer (text)
       (let ((pos (search "ABC" text)))
            (if pos
                (progn
                  (incf counter)
                  (answer (subseq text (+ pos 2))))
                counter))))

(print (answer (cur s)))

Score : 600 points

Problem Statement

You are given a string s consisting of A, B and C.

Snuke wants to perform the following operation on s as many times as possible:

Choose a contiguous substring of s that reads ABC and replace it with BCA.

Find the maximum possible number of operations.

Constraints

1 \leq |s| \leq 200000

Each character of s is A, B and C.

Input

Input is given from Standard Input in the following format:

s

Output

Find the maximum possible number of operations.

Sample Input 1

ABCABC

Sample Output 1

3

You can perform the operations three times as follows: ABCABC → BCAABC → BCABCA → BCBCAA. This is the maximum result.

Sample Input 2

C

Sample Output 2

0

Sample Input 3

ABCACCBABCBCAABCB

Sample Output 3

6


(defparameter s (read-line))

(defun cut (text)
  (if (equal "BC" (subseq text 0 2))
      (cut (subseq text 2))
      (if (or (equal "C" (subseq text 0 1))
              (equal "B" (subseq text 0 1)))
          (cut (subseq text 1))
          text)))

(let ((counter 0))
     (defun answer (text)
       (let* ((new-text (cut text))
              (pos (search "ABC" text)))
             (if pos
                (progn
                  (setf (subseq new-text pos (+ pos 3)) "BCA")
                  (incf counter)
                  (answer new-text))
                counter))))

(print (answer s))


(defparameter s (read))

(let ((counter 0))
     (defun answer (text)
       (let ((pos (search "ABC" text)))
            (if pos
                (progn
                  (setf (subseq text pos (+ pos 3)) "BCA")
                  (setf counter (1+ counter))
                  (answer text))
                counter))))

(print (answer s))


(declaim (optimize (debug 0) (safety 0) (speed 3)))
(defun blacken (grid queue1 queue2 cnt)
  (loop while (< 0 (length queue1)) do
        (loop
          with i = (vector-pop queue1)
          with j = (vector-pop queue1)
          for (a b) in '((0 1) (0 -1) (1 0) (-1 0)) do
            (if (< (1+ cnt) (aref grid (+ i a) (+ j b)))
              (progn
                (setf (aref grid (+ i a) (+ j b)) (1+ cnt))
                (vector-push-extend (+ i a) queue2)
                (vector-push-extend (+ j b) queue2)))))
  (if (= 0 (length queue2))
    cnt
    (blacken grid queue2 queue1 (1+ cnt))))

(defun main ()
  (let* ((h (read))
         (w (read))
         (grid (make-array (list (+ h 2) (+ w 2))
                           :initial-element 0))
         (queue (make-array 0 :fill-pointer 0 :adjustable t)))
    (loop for i from 1 to h do
          (loop for j from 1 to w
                for c in (concatenate 'list (read-line)) do
                (if (equal c #\.)
                  (setf (aref grid i j) 9999999)
                  (progn
                    (setf (aref grid i j) 0)
                    (vector-push-extend i queue)
                    (vector-push-extend j queue)))))
    (format t "~a~%"
      (blacken grid
               queue
               (make-array 0 :fill-pointer 0 :adjustable t)
               0))))
(main)

Score : 300 points

Problem Statement

You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black.
HW characters from A_{11} to A_{HW} represent the colors of the squares.
A_{ij} is # if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is . if that square is white.

We will repeatedly perform the following operation until all the squares are black:

Every white square that shares a side with a black square, becomes black.

Find the number of operations that will be performed.
The initial grid has at least one black square.

Constraints

1 \leq H,W \leq 1000

A_{ij} is # or ..

The given grid has at least one black square.

Input

Input is given from Standard Input in the following format:

H W
A_{11}A_{12}...A_{1W}
:
A_{H1}A_{H2}...A_{HW}

Output

Print the number of operations that will be performed.

Sample Input 1

3 3
...
.#.
...

Sample Output 1

2

After one operation, all but the corners of the grid will be black. After one more operation, all the squares will be black.

Sample Input 2

6 6
..#..#
......
#..#..
......
.#....
....#.

Sample Output 2

3


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

;; BEGIN_INSERTED_CONTENTS
(declaim (inline fast-read-char))
(defun fast-read-char (stream)
  (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))))

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

(declaim (inline enqueue))
(defun enqueue (obj 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)
  (pop (queue-list queue)))

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

(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 ()
  (declare #.OPT)
  (let* ((h (read))
         (w (read))
         (plan (make-array '(1002 1002) :element-type 'uint16 :initial-element 0))
         ;; i|j
         (q (make-queue)))
    (declare (uint32 h w))
    (loop for i from 1 to h
          do (loop for j from 1 to w
                   do (if (char= #\# (fast-read-char *standard-input*))
                          (enqueue (logxor i (ash j 16)) q)
                          (setf (aref plan i j) #xffff)))
             (fast-read-char *standard-input*))
    (labels ((frob (next-d next-i next-j)
               (declare (uint32 next-d next-i next-j))
               (when (= #xffff (aref plan next-i next-j))
                 (enqueue (logxor next-i (ash next-j 16)) q)
                 (setf (aref plan next-i next-j) next-d))))
      (declare (inline frob))
      (loop until (queue-empty-p q)
            for node of-type uint32 = (dequeue q)
            for i = (logand #.(ldb (byte 16 0) -1) node)
            for j = (ash node -16)
            for d = (aref plan i j)
            do (frob (+ 1 d) (- i 1) j)
               (frob (+ 1 d) (+ i 1) j)
               (frob (+ 1 d) i (- j 1))
               (frob (+ 1 d) i (+ j 1))))
    (println (loop for x across (array-storage-vector plan) maximize x))))

#-swank(main)


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

;; BEGIN_INSERTED_CONTENTS
(declaim (inline fast-read-char))
(defun fast-read-char (stream)
  (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))))

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

(declaim (inline enqueue))
(defun enqueue (obj 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)
  (pop (queue-list queue)))

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

(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 ()
  (declare #.OPT)
  (let* ((h (read))
         (w (read))
         (plan (make-array '(1000 1000) :element-type 'uint16 :initial-element 0))
         ;; i|j
         (q (make-queue)))
    (declare (uint32 h w))
    (dotimes (i h)
      (dotimes (j w)
        (if (char= #\# (fast-read-char *standard-input*))
            (enqueue (logxor i (ash j 16)) q)
            (setf (aref plan i j) #xffff)))
      (fast-read-char *standard-input*))
    (labels ((frob (next-d next-i next-j)
               (declare (uint32 next-d next-i next-j))
               (when (= #xffff (aref plan next-i next-j))
                 (enqueue (logxor next-i (ash next-j 16)) q)
                 (setf (aref plan next-i next-j) next-d))))
      (declare (inline frob))
      (loop until (queue-empty-p q)
            for node of-type uint32 = (dequeue q)
            for i = (logand #.(ldb (byte 16 0) -1) node)
            for j = (ash node -16)
            for d = (aref plan i j)
            do (when (< 0 i)
                 (frob (+ 1 d) (- i 1) j))
               (when (< i (- h 1))
                 (frob (+ 1 d) (+ i 1) j))
               (when (< 0 j)
                 (frob (+ 1 d) i (- j 1)))
               (when (< j (- w 1))
                 (frob (+ 1 d) i (+ j 1)))))
    (println (loop for x across (array-storage-vector plan) maximize x))))

#-swank(main)