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

;; BEGIN_INSERTED_CONTENTS
;;;
;;; Arithmetic operations with static modulus
;;;

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

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

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

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

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

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

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

;;;
;;; Body
;;;

(define-mod-operations +mod+)

(defun main ()
  (let* ((n (read))
         (s (read))
         (as (make-array n :element-type 'uint32))
         (dp (make-array (list (+ n 1) 11) :element-type 'uint32 :initial-element 0))
         (res 0))
    (dotimes (i n)
      (setf (aref as i) (read)))
    (dotimes (x n)
      #>dp
      (let ((a (aref as x)))
        (dotimes (y s)
          (setf (aref dp (+ x 1) y) (aref dp x y)))
        (incfmod (aref dp (+ x 1) a) (+ x 1))
        (dotimes (y (+ s 1))
          (when (> (+ y a) s)
            (return))
          (incfmod (aref dp (+ x 1) (+ y a))
                   (aref dp x y)))
        (incfmod res #>(mod* (- n x) (aref dp (+ x 1) s)))))
    #>dp
    (println res)))

#-swank (main)

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

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

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

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

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

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

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

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

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


(defvar N (read))

(defun abskaisa (old &optional new)
  (if (null (cdr old))
      (nreverse new)
    (abskaisa (cdr old) (cons (abs (- (cadr old) (car old))) new))))

(defun solve-stupid ()
  (let ((a (mapcar #'digit-char-p (concatenate 'list (read-line)))))
    (dotimes (x (1- N))
      (setf a (abskaisa a))
      )
    (princ (car a))
    )
  )

(defun cunning-solve ()
  (let* ((str (read-line))
	 (hd (mapcar #'digit-char-p (concatenate 'list (subseq str 0 4))))
	 (tl (mapcar #'digit-char-p (concatenate 'list (subseq str (- N 4)))))
	 (hdb (abskaisa (abskaisa hd)))
	 )
    (princ (list hdb tl))))

(solve-stupid)

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

Score : 700 points

Problem Statement

Given is a sequence of N digits a_1a_2\ldots a_N, where each element is 1, 2, or 3.
Let x_{i,j} defined as follows:

x_{1,j} := a_j \quad (1 \leq j \leq N)

x_{i,j} := | x_{i-1,j} - x_{i-1,j+1} | \quad (2 \leq i \leq N and 1 \leq j \leq N+1-i)

Find x_{N,1}.

Constraints

2 \leq N \leq 10^6

a_i = 1,2,3 (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N
a_1a_2\ldotsa_N

Output

Print x_{N,1}.

Sample Input 1

4
1231

Sample Output 1

1

x_{1,1},x_{1,2},x_{1,3},x_{1,4} are respectively 1,2,3,1.

x_{2,1},x_{2,2},x_{2,3} are respectively |1-2| = 1,|2-3| = 1,|3-1| = 2.

x_{3,1},x_{3,2} are respectively |1-1| = 0,|1-2| = 1.

Finally, x_{4,1} = |0-1| = 1, so the answer is 1.

Sample Input 2

10
2311312312

Sample Output 2

0

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.


(defun main ()
  (let* ((n (read))
         (vec (make-array n :initial-element 0)))
    (dotimes (i n)
      (setf (svref vec i)
            (- (char-code (read-char)) 48)))
    (princ (f n vec))))

(defun f (n vec)
  (let ((cache (make-hash-table :test #'equal)))
    (labels ((x (i j)
               (declare (optimize (speed 3))
                        (type fixnum i j))
               (or (identity (gethash (cons i j) cache))
                   (setf (gethash (cons i j) cache)
                         (if (<= i 0)
                             (svref vec j)
                             (abs (the fixnum (- (the fixnum (x (1- i) j))
                                                 (the fixnum (x (1- i) (1+ j)))))))))))
      (x (1- n) 0))))

(main)


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

;; BEGIN_INSERTED_CONTENTS
(defmacro 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 solve (a b c)
  (declare #.OPT
           (simple-base-string a b c))
  (let ((len-a (length a))
        (len-b (length b))
        (len-c (length c))
        (ab (make-string 4000 :element-type 'base-char))
        (min #xffffffff))
    (declare (uint32 len-a len-b len-c min))
    (dotimes (init1 (+ len-a 1))
      (block outer
        (loop for i from init1 below len-a
              for j from 0 below len-b
              unless (or (char= (aref a i) (aref b j))
                         (char= (aref a i) #\?)
                         (char= (aref b j) #\?))
              do (return-from outer)
              finally
                 (let ((len-ab (max len-a (+ init1 len-b))))
                   (dotimes (i len-a)
                     (setf (aref ab i) (aref a i)))
                   (loop for j below len-b
                         for i = (+ j init1)
                         do (cond ((>= i len-a)
                                   (setf (aref ab i) (aref b j)))
                                  ((char= #\? (aref a i) (aref b j))
                                   (setf (aref ab i) #\?))
                                  ((char= #\? (aref a i))
                                   (setf (aref ab i) (aref b j)))
                                  ((char= #\? (aref b j))
                                   (setf (aref ab i) (aref a i)))
                                  (t
                                   (setf (aref ab i) (aref b j)))))
                   (dotimes (init2 (+ len-ab 1))
                     (when (>= (max len-ab (+ init2 len-c)) min)
                       (return))
                     (block inner
                       (loop for i from init2 below len-ab
                             for j from 0 below len-c
                             unless (or (char= (aref ab i) (aref c j))
                                        (char= (aref ab i) #\?)
                                        (char= (aref c j) #\?))
                             do (return-from inner)
                             finally (setq min (min min (max len-ab (+ init2 len-c)))))))))))
    min))

(defun main ()
  (let* ((a (coerce (read-line) 'simple-base-string))
         (b (coerce (read-line) 'simple-base-string))
         (c (coerce (read-line) 'simple-base-string)))
    ;; (solve b a c)
    (println
     (min (solve a b c)
          (solve a c b)
          (solve b c a)
          (solve b a c)
          (solve c a b)
          (solve c b a)))
    ))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "a?c
der
cod
"
    "7
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "atcoder
atcoder
???????
"
    "7
")))

Score : 500 points

Problem Statement

Snuke has a string s.
From this string, Anuke, Bnuke, and Cnuke obtained strings a, b, and c, respectively, as follows:

Choose a non-empty (contiguous) substring of s (possibly s itself). Then, replace some characters (possibly all or none) in it with ?s.

For example, if s is mississippi, we can choose the substring ssissip and replace its 1-st and 3-rd characters with ? to obtain ?s?ssip.

You are given the strings a, b, and c.
Find the minimum possible length of s.

Constraints

1 \leq |a|, |b|, |c| \leq 2000

a, b, and c consists of lowercase English letters and ?s.

Input

Input is given from Standard Input in the following format:

a
b
c

Output

Print the minimum possible length of s.

Sample Input 1

a?c
der
cod

Sample Output 1

7

For example, s could be atcoder.

Sample Input 2

atcoder
atcoder
???????

Sample Output 2

7

a, b, and c may not be distinct.


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

;; BEGIN_INSERTED_CONTENTS
(defmacro 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 solve (a b c)
  (declare #.OPT
           (simple-base-string a b c))
  (let ((len-a (length a))
        (len-b (length b))
        (len-c (length c))
        (min #xffffffff))
    (declare (uint32 len-a len-b len-c min))
    (dotimes (init1 (+ len-a 1))
      (block outer
        (loop for i from init1 below len-a
              for j from 0 below len-b
              unless (or (char= (aref a i) (aref b j))
                         (char= (aref a i) #\?)
                         (char= (aref b j) #\?))
              do (return-from outer)
              finally
                 (let ((ab (make-string (+ init1 len-b) :element-type 'base-char)))
                   (dotimes (i init1)
                     (setf (aref ab i) (aref a i)))
                   (loop for j below len-b
                         for i = (+ j init1)
                         do (cond ((>= i len-a)
                                   (setf (aref ab i) (aref b j)))
                                  ((char= #\? (aref a i) (aref b j))
                                   (setf (aref ab i) #\?))
                                  ((char= #\? (aref a i))
                                   (setf (aref ab i) (aref b j)))
                                  ((char= #\? (aref b j))
                                   (setf (aref ab i) (aref a i)))
                                  (t
                                   ;; (assert (char= (aref a i) (aref b j)))
                                   (setf (aref ab i) (aref b j)))))
                   (let ((len-ab (length ab)))
                     (dotimes (init2 (+ len-ab 1))
                       (block inner
                         (loop for i from init2 below len-ab
                               for j from 0 below len-c
                               unless (or (char= (aref ab i) (aref c j))
                                          (char= (aref ab i) #\?)
                                          (char= (aref c j) #\?))
                               do (return-from inner)
                               finally (setq min (min min (+ init2 len-c)))))))))))
    min))

(defun main ()
  (let* ((a (coerce (read-line) 'simple-base-string))
         (b (coerce (read-line) 'simple-base-string))
         (c (coerce (read-line) 'simple-base-string)))
    ;; (solve c a b)
    (println
     (min (solve a b c)
          (solve a c b)
          #>(solve b c a)
          #>(solve b a c)
          #>(solve c a b)
          #>(solve c b a)))
    ))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "a?c
der
cod
"
    "7
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "atcoder
atcoder
???????
"
    "7
")))


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

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

(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 encode (x)
  (let ((res (make-array 31 :element-type 'uint8)))
    (dotimes (i 31)
      (multiple-value-bind (quot rem) (floor x 3)
        (setf (aref res i) rem
              x quot)))
    res))

(defun decode (x)
  (let ((base 1)
        (res 0))
    (dotimes (i 31)
      (incf res (* base (aref x i)))
      (setq base (* base 3)))
    res))

(defun main ()
  (let* ((q (read)))
    (dotimes (_ q)
      (let* ((a (- (read-fixnum) 1))
             (b (- (read-fixnum) 1))
             (c (- (read-fixnum) 1))
             (d (- (read-fixnum) 1))
             (as (encode a))
             (bs (encode b))
             (cs (encode c))
             (ds (encode d))
             (depth (max (loop for i from 30 downto -1
                               do (when (or (= -1 i)
                                            (/= (aref as i) (aref cs i)))
                                    (return i)))
                         (loop for i from 30 downto -1
                               do (when (or (= -1 i)
                                            (/= (aref bs i) (aref ds i)))
                                    (return i))))))
        (loop for i from 30 above depth
              do (setf (aref as i) 0
                       (aref bs i) 0
                       (aref cs i) 0
                       (aref ds i) 0))
        ; (dbg as bs cs ds)
        (let* ((a (decode as))
               (b (decode bs))
               (c (decode cs))
               (d (decode ds))
               (base (expt 3 depth))
               (aseg (floor a base))
               (bseg (floor b base))
               (cseg (floor c base))
               (dseg (floor d base)))
          (dbg a b c d)
          (dbg aseg bseg cseg dseg)
          (let ((res (+ (abs (- a c)) (abs (- b d)))))
            #>res
            (cond ((or (and (= aseg 1) (= bseg 0) (= cseg 1) (= dseg 2))
                       (and (= aseg 1) (= bseg 2) (= cseg 1) (= dseg 0)))
                   (assert (and (>= a base) (>= c base)))
                   (incf res (min #>(* 2 (- (min a c) (- base 1)))
                                  #>(* 2 (- (* 2 base) (max a c))))))
                  ((or (and (= aseg 0) (= bseg 1) (= cseg 2) (= dseg 1))
                       (and (= aseg 2) (= bseg 1) (= cseg 0) (= dseg 1)))
                   (assert (and (>= b base) (>= d base)))
                   (incf res (min (* 2 (- (min b d) (- base 1)))
                                  (* 2 (- (* 2 base) (max b d))))))
                  (t))
            (println res)))))))

#-swank (main)

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

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

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

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

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

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

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

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

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

Score : 600 points

Problem Statement

For a non-negative integer K, we define a fractal of level K as follows:

A fractal of level 0 is a grid with just one white square.

When K > 0, a fractal of level K is a 3^K \times 3^K grid. If we divide this grid into nine 3^{K-1} \times 3^{K-1} subgrids:

The central subgrid consists of only black squares.

Each of the other eight subgrids is a fractal of level K-1.

For example, a fractal of level 2 is as follows:

In a fractal of level 30, let (r, c) denote the square at the r-th row from the top and the c-th column from the left.

You are given Q quadruples of integers (a_i, b_i, c_i, d_i).
For each quadruple, find the distance from (a_i, b_i) to (c_i, d_i).

Here the distance from (a, b) to (c, d) is the minimum integer n that satisfies the following condition:

There exists a sequence of white squares (x_0, y_0), \ldots, (x_n, y_n) satisfying the following conditions:

(x_0, y_0) = (a, b)

(x_n, y_n) = (c, d)

For every i (0 \leq i \leq n-1), (x_i, y_i) and (x_{i+1}, y_{i+1}) share a side.

Constraints

1 \leq Q \leq 10000

1 \leq a_i, b_i, c_i, d_i \leq 3^{30}

(a_i, b_i) \neq (c_i, d_i)

(a_i, b_i) and (c_i, d_i) are white squares.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

Q
a_1 \ b_1 \ c_1 \ d_1
:
a_Q \ b_Q \ c_Q \ d_Q

Output

Print Q lines.
The i-th line should contain the distance from (a_i, b_i) to (c_i, d_i).

Sample Input 1

2
4 2 7 4
9 9 1 9

Sample Output 1

5
8


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

(defun main ()
  (let* ((a-num (read))
	 (b-num (read))
	 (m-num (read))
	 (a-price (make-array a-num))
	 (b-price (make-array b-num))
	 (price 100000))
    (dotimes (n a-num)
      (setf (aref a-price n) (read-fixnum)))
    (dotimes (n b-num)
      (setf (aref b-price n) (read-fixnum)))
    (dotimes (i m-num)
      (let* ((a-disc-idx (read-fixnum))
	     (b-disc-idx (read-fixnum))
	     (disc-price (read-fixnum))
	     (result (- (+ (aref a-price (1- a-disc-idx)) (aref b-price (1- b-disc-idx))) disc-price)))
	(if (< result price)
	    (setq price result))))
    (setq a-price (sort a-price #'<))
    (setq b-price (sort b-price #'<))
    (if (< (+ (aref a-price 0) (aref b-price 0)) price)
	(setq price (+ (aref a-price 0) (aref b-price 0))))
    (format t "~a~%" price)))

(main)

Score : 200 points

Problem Statement

You are visiting a large electronics store to buy a refrigerator and a microwave.

The store sells A kinds of refrigerators and B kinds of microwaves. The i-th refrigerator ( 1 \le i \le A ) is sold at a_i yen (the currency of Japan), and the j-th microwave ( 1 \le j \le B ) is sold at b_j yen.

You have M discount tickets. With the i-th ticket ( 1 \le i \le M ), you can get a discount of c_i yen from the total price when buying the x_i-th refrigerator and the y_i-th microwave together. Only one ticket can be used at a time.

You are planning to buy one refrigerator and one microwave. Find the minimum amount of money required.

Constraints

All values in input are integers.

1 \le A \le 10^5

1 \le B \le 10^5

1 \le M \le 10^5

1 \le a_i , b_i , c_i \le 10^5

1 \le x_i \le A

1 \le y_i \le B

c_i \le a_{x_i} + b_{y_i}

Input

Input is given from Standard Input in the following format:

A B M
a_1 a_2 ... a_A
b_1 b_2 ... b_B
x_1 y_1 c_1
\vdots
x_M y_M c_M

Output

Print the answer.

Sample Input 1

2 3 1
3 3
3 3 3
1 2 1

Sample Output 1

5

With the ticket, you can get the 1-st refrigerator and the 2-nd microwave for 3+3-1=5 yen.

Sample Input 2

1 1 2
10
10
1 1 5
1 1 10

Sample Output 2

10

Note that you cannot use more than one ticket at a time.

Sample Input 3

2 2 1
3 5
3 5
2 2 2

Sample Output 3

6

You can get the 1-st refrigerator and the 1-st microwave for 6 yen, which is the minimum amount to pay in this case.
Note that using a ticket is optional.


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

;; BEGIN_INSERTED_CONTENTS
(macrolet ((def (name fname)
             `(define-modify-macro ,name (new-value) ,fname)))
  (def minf min)
  (def maxf max)
  (def mulf *)
  (def divf /)
  (def iorf logior)
  (def xorf logxor)
  (def andf logand))

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

(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* ((a (read))
         (b (read))
         (m (read))
         (as (make-array a :element-type 'uint32))
         (bs (make-array b :element-type 'uint32)))
    (dotimes (i a)
      (setf (aref as i) (read-fixnum)))
    (dotimes (i b)
      (setf (aref bs i) (read-fixnum)))
    (let ((res (+ (reduce #'min as)
                  (reduce #'min bs))))
      (dotimes (i m)
        (let ((x (- (read-fixnum) 1))
              (y (- (read-fixnum) 1))
              (c (read-fixnum)))
          (minf res (- (+ (aref as x)
                          (aref bs y))
                       c))))
      (println res))))

#-swank (main)

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

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

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

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

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

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

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

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

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


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

;; BEGIN_INSERTED_CONTENTS
(macrolet ((def (name fname)
             `(define-modify-macro ,name (new-value) ,fname)))
  (def minf min)
  (def maxf max)
  (def mulf *)
  (def divf /)
  (def iorf logior)
  (def xorf logxor)
  (def andf logand))

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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defconstant +inf+ #x7fffffff)

(defun main ()
  (declare #.OPT
           (inline sort))
  (let* ((n (read))
         (limit (read))
         (bs (make-array n :element-type 'uint32 :fill-pointer 0))
         (abs (make-array n :element-type '(cons uint31 uint31) :fill-pointer 0)))
    (declare (uint31 n limit))
    (dotimes (i n)
      (let ((a (read-fixnum))
            (b (read-fixnum)))
        (if (zerop a)
            (vector-push (+ b 1) bs)
            (vector-push (cons a b) abs))))
    (setq bs (sort bs #'<))
    (setq abs (sort abs
                    (lambda (node1 node2)
                      (let ((a1 (car node1))
                            (b1 (cdr node1))
                            (a2 (car node2))
                            (b2 (cdr node2)))
                        (declare (uint31 a1 b1 a2 b2))
                        (<= (* a2 (+ b1 1)) (* a1 (+ b2 1)))))))
    (let* ((n1 (length abs))
           (n2 (length bs))
           (cumuls (make-array (+ n2 1) :element-type 'uint31 :initial-element 0))
           (dp (make-array '(200001 31) :element-type 'uint31 :initial-element +inf+)))
      (setf (aref dp 0 0) 0)
      (dotimes (i n2)
        (setf (aref cumuls (+ i 1))
              (min +inf+ (+ (aref cumuls i) (aref bs i)))))
      (dotimes (x n1)
        (destructuring-bind (a . b) (aref abs x)
          (declare (uint31 a b))
          (dotimes (y 31)
            (minf (aref dp (+ x 1) y) (aref dp x y))
            (when (< y 30)
              (minf (aref dp (+ x 1) (+ y 1))
                    (+ b (* (+ a 1) (+ (aref dp x y) 1))))))))
      (let ((res 0))
        (declare (uint31 res))
        (loop for y from 30 downto 0
              for pos = n2
              do (loop for x from n1 downto 0
                       do (loop until (or (<= (+ (aref dp x y) (aref cumuls pos)) limit)
                                          (zerop pos))
                                do (decf pos))
                          (when (<= (+ (aref dp x y) (aref cumuls pos)) limit)
                            (maxf res (+ y pos)))))
        (println res)))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3 7
2 0
3 2
0 3
"
    "2
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "1 3
0 3
"
    "0
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "5 21600
2 14
3 22
1 3
1 10
1 9
"
    "5
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "7 57
0 25
3 10
2 4
5 15
3 22
2 14
1 15
"
    "3
")))

Score : 800 points

Problem Statement

There are N stores called Store 1, Store 2, \cdots, Store N. Takahashi, who is at his house at time 0, is planning to visit some of these stores.

It takes Takahashi one unit of time to travel from his house to one of the stores, or between any two stores.

If Takahashi reaches Store i at time t, he can do shopping there after standing in a queue for a_i \times t + b_i units of time. (We assume that it takes no time other than waiting.)

All the stores close at time T + 0.5. If Takahashi is standing in a queue for some store then, he cannot do shopping there.

Takahashi does not do shopping more than once in the same store.

Find the maximum number of times he can do shopping before time T + 0.5.

Constraints

All values in input are integers.

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

0 \leq a_i \leq 10^9

0 \leq b_i \leq 10^9

0 \leq T \leq 10^9

Input

Input is given from Standard Input in the following format:

N T
a_1 b_1
a_2 b_2
\vdots
a_N b_N

Output

Print the answer.

Sample Input 1

3 7
2 0
3 2
0 3

Sample Output 1

2

Here is one possible way to visit stores:

From time 0 to time 1: in 1 unit of time, he travels from his house to Store 1.

From time 1 to time 3: for 2 units of time, he stands in a queue for Store 1 to do shopping.

From time 3 to time 4: in 1 unit of time, he travels from Store 1 to Store 3.

From time 4 to time 7: for 3 units of time, he stands in a queue for Store 3 to do shopping.

In this way, he can do shopping twice before time 7.5.

Sample Input 2

1 3
0 3

Sample Output 2

0

Sample Input 3

5 21600
2 14
3 22
1 3
1 10
1 9

Sample Output 3

5

Sample Input 4

7 57
0 25
3 10
2 4
5 15
3 22
2 14
1 15

Sample Output 4

3


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

;; BEGIN_INSERTED_CONTENTS
(macrolet ((def (name fname)
             `(define-modify-macro ,name (new-value) ,fname)))
  (def minf min)
  (def maxf max)
  (def mulf *)
  (def divf /)
  (def iorf logior)
  (def xorf logxor)
  (def andf logand))

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

(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 (inline sort))
  (let* ((n (read))
         (limit (read))
         (bs (make-array n :element-type 'uint32 :fill-pointer 0))
         (abs (make-array n :element-type '(cons uint31 uint31) :fill-pointer 0)))
    (dotimes (i n)
      (let ((a (read-fixnum))
            (b (read-fixnum)))
        (if (zerop a)
            (vector-push (+ b 1) bs)
            (vector-push (cons a b) abs))))
    (setq abs (sort abs
                    (lambda (node1 node2)
                      (let ((a1 (car node1))
                            (b1 (cdr node1))
                            (a2 (car node2))
                            (b2 (cdr node2)))
                        (declare (uint31 a1 b1 a2 b2))
                        (<= (* a2 (+ b1 1)) (* a1 (+ b2 1)))))))
    (let* ((n1 (length abs))
           (n2 (length bs))
           (cumuls (make-array (+ n2 1) :element-type 'uint62 :initial-element 0))
           (dp (make-array (list (+ n1 1) 31)
                           :element-type 'uint62
                           :initial-element most-positive-fixnum)))
      (setf (aref dp 0 0) 0)
      (dotimes (i n2)
        (setf (aref cumuls (+ i 1))
              (+ (aref cumuls i) (aref bs i))))
      (dotimes (x n1)
        (destructuring-bind (a . b) (aref abs x)
          (declare (uint31 a b))
          (dotimes (y 31)
            (minf (aref dp (+ x 1) y) (aref dp x y))
            (when (< y 30)
              (minf (aref dp (+ x 1) (+ y 1))
                    (+ b (* (+ a 1) (+ (aref dp x y) 1))))))))
      #>dp
      #>bs
      #>cumuls
      (let ((res 0))
        (loop for y from 30 downto 0
              for pos = n2
              do (loop for x from n1 downto 0
                       do (loop until (or (<= (+ (aref dp x y) (aref cumuls pos)) limit)
                                          (zerop pos))
                                do (decf pos))
                          (when (<= (+ (aref dp x y) (aref cumuls pos)) limit)
                            (maxf res (+ y pos)))))
        (println res)))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3 7
2 0
3 2
0 3
"
    "2
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "1 3
0 3
"
    "0
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "5 21600
2 14
3 22
1 3
1 10
1 9
"
    "5
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "7 57
0 25
3 10
2 4
5 15
3 22
2 14
1 15
"
    "3
")))


(let*  ((N (read))
        (A (read))
        (B (read)))
  (if (= A 0)
      (princ 0)
      (let ((ans (* (/ N (+ A B)) A))
            (remainder (mod N (+ A B))))
        (princ (floor (+ ans (if (< remainder A) remainder A)))))))

Score : 200 points

Problem Statement

Takahashi has many red balls and blue balls. Now, he will place them in a row.

Initially, there is no ball placed.

Takahashi, who is very patient, will do the following operation 10^{100} times:

Place A blue balls at the end of the row of balls already placed. Then, place B red balls at the end of the row.

How many blue balls will be there among the first N balls in the row of balls made this way?

Constraints

1 \leq N \leq 10^{18}

A, B \geq 0

0 < A + B \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the number of blue balls that will be there among the first N balls in the row of balls.

Sample Input 1

8 3 4

Sample Output 1

4

Let b denote a blue ball, and r denote a red ball. The first eight balls in the row will be bbbrrrrb, among which there are four blue balls.

Sample Input 2

8 0 4

Sample Output 2

0

He placed only red balls from the beginning.

Sample Input 3

6 2 4

Sample Output 3

2

Among bbrrrr, there are two blue balls.


(let*  ((N (read))
        (A (read))
        (tmp (+ A (read)))
        (ans (/ (float N) tmp))
        (remainder (mod (float N) tmp)))
  (if (= A 0)
      (princ 0)
      (princ (+ ans (floor (if (< remainder A) remainder A))))))


(format t "~d~%"
	(loop with n = (read)
	   with a = (read)
	   with b = (read)
	   repeat (expt 10 100)
	   sum a into i
	   sum a into r
	   thereis (and (< n i)
			(- r (- i n)))
	   sum b into i
	   thereis (and (< n i) r)))


(defun count-balls ()
  (let ((n (read))
        (b (read))
        (r (read))
        (ans 0))
    (setf ans (+ (* b (floor n (+ b r))) (min b  (rem n (+ b r)))))
    ans))

(format t "~d~%" (count-balls))


(defun solve (n a b)
  (multiple-value-bind (div quot)
      (truncate n (+ a b))
    (+ (* div a)
       (if (< (- quot a) 0)
           quot
           a))))

#-swank
(let* ((n (read))
       (a (read))
       (b (read)))
  (format t "~A~%" (solve n a b)))


(let* ((a (read))
       (b (read))
       (c (find-if (lambda (x) (find x (loop for i upfrom (floor b 0.1) repeat 9 collect i)))
		   (loop for i upfrom (floor a 0.08) repeat 12 collect i))))
  (format t "~:[-1~;~d~]~%" (and (= a (floor (* c 0.08))) (= b (floor (* c 0.1)))) c))

Score : 300 points

Problem Statement

Find the price of a product before tax such that, when the consumption tax rate is 8 percent and 10 percent, the amount of consumption tax levied on it is A yen and B yen, respectively. (Yen is the currency of Japan.)

Here, the price before tax must be a positive integer, and the amount of consumption tax is rounded down to the nearest integer.

If multiple prices satisfy the condition, print the lowest such price; if no price satisfies the condition, print -1.

Constraints

1 \leq A \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If there is a price that satisfies the condition, print an integer representing the lowest such price; otherwise, print -1.

Sample Input 1

2 2

Sample Output 1

25

If the price of a product before tax is 25 yen, the amount of consumption tax levied on it is:

When the consumption tax rate is 8 percent: \lfloor 25 \times 0.08 \rfloor = \lfloor 2 \rfloor = 2 yen.

When the consumption tax rate is 10 percent: \lfloor 25 \times 0.1 \rfloor = \lfloor 2.5 \rfloor = 2 yen.

Thus, the price of 25 yen satisfies the condition. There are other possible prices, such as 26 yen, but print the minimum such price, 25.

Sample Input 2

8 10

Sample Output 2

100

If the price of a product before tax is 100 yen, the amount of consumption tax levied on it is:

When the consumption tax rate is 8 percent: \lfloor 100 \times 0.08 \rfloor = 8 yen.

When the consumption tax rate is 10 percent: \lfloor 100 \times 0.1 \rfloor = 10 yen.

Sample Input 3

19 99

Sample Output 3

-1

There is no price before tax satisfying this condition, so print -1.


(let* ((s (read-line))
       (q (read))
       (head nil)
       (tail nil)
       (rev 0))
  (loop :for i :from 1 :to q
        :for x := (read)
        :if (= x 1)
        :do (progn
              (incf rev))
        :else
        :do (let ((f (read))
                  (c (read-char)))
              (cond ((and (evenp rev) (= f 1))
                     (push c head))
                    ((and (evenp rev) (= f 2))
                     (push c tail))
                    ((and (oddp rev) (= f 1))
                     (push c tail))
                    (t
                     (push c head)))))
  (when (oddp rev)
    (rotatef head tail)
    (setf s (reverse s)))
  (loop :for c :in head :do (format t "~A" c))
  (format t "~A" s)
  (loop :for c :in (reverse tail) :do (format t "~A" c))
  (format t "~%"))

Score : 400 points

Problem Statement

Takahashi has a string S consisting of lowercase English letters.

Starting with this string, he will produce a new one in the procedure given as follows.

The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following:

If T_i = 1: reverse the string S.

If T_i = 2: An integer F_i and a lowercase English letter C_i are additionally provided.

If F_i = 1 : Add C_i to the beginning of the string S.

If F_i = 2 : Add C_i to the end of the string S.

Help Takahashi by finding the final string that results from the procedure.

Constraints

1 \leq |S| \leq 10^5

S consists of lowercase English letters.

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

T_i = 1 or 2.

F_i = 1 or 2, if provided.

C_i is a lowercase English letter, if provided.

Input

Input is given from Standard Input in the following format:

S
Q
Query_1
:
Query_Q

In the 3-rd through the (Q+2)-th lines, Query_i is one of the following:

1

which means T_i = 1, and:

2 F_i C_i

which means T_i = 2.

Output

Print the resulting string.

Sample Input 1

a
4
2 1 p
1
2 2 c
1

Sample Output 1

cpa

There will be Q = 4 operations. Initially, S is a.

Operation 1: Add p at the beginning of S. S becomes pa.

Operation 2: Reverse S. S becomes ap.

Operation 3: Add c at the end of S. S becomes apc.

Operation 4: Reverse S. S becomes cpa.

Thus, the resulting string is cpa.

Sample Input 2

a
6
2 2 a
2 1 b
1
2 2 c
1
1

Sample Output 2

aabc

There will be Q = 6 operations. Initially, S is a.

Operation 1: S becomes aa.

Operation 2: S becomes baa.

Operation 3: S becomes aab.

Operation 4: S becomes aabc.

Operation 5: S becomes cbaa.

Operation 6: S becomes aabc.

Thus, the resulting string is aabc.

Sample Input 3

y
1
2 1 x

Sample Output 3

xy


(defvar char-list
        (loop :as char
              :across (read-line)
              :collect char))
(defvar tale (last char-list))
(defvar qs (read))
(defvar reversep nil)

(defun enqueue (N)
  (rplacd tale (list N))
  (setf tale (cdr tale)))

(defun add-char (end-p char)
  (if (or (and reversep end-p)
          (and (null reversep)
               (null end-p)))
      (push char char-list)
      (enqueue char)))

(defun do-query (q)
  (case q
    (1 (setf reversep (not reversep)))
    (2 (add-char (= 2 (read)) (read-char)))))

  (loop :repeat qs :do (do-query (read)))
  (format t "~{~A~^~}" (if reversep (reverse char-list) char-list))


(defvar char-list (list (read-line)))
(defvar tale (last char-list))
(defvar qs (read))
(defvar reversep nil)

(defun enqueue (N)
  (rplacd tale (list N))
  (setf tale (cdr tale)))

(defun add-char (end-p char)
  (if (or (and reversep end-p)
          (and (null reversep)
               (null end-p)))
      (push char char-list)
      (enqueue char)))

(defun do-query (q)
  (case q
    (1 (setf reversep (not reversep)))
    (2 (add-char (= 2 (read)) (read-char)))))

  (loop :repeat qs :do (do-query (read)))
  (format t "~{~A~^~}" (if reversep (reverse char-list) char-list))


(let* ((s (read-line))
       (size 400000)
       (buf (make-array size))
       (q (read))
       (parity nil)
       (head (- size 1))
       (len (length s))
       (tail len))
  (loop for i from 0 below (length s)
        do (setf (aref buf i) (aref s i)))

  (loop repeat q
        for query = (read)
        do (if (= query 1)
               (setf parity (not parity))
               (let ((f (read))
                     (c (read-char)))
                 (incf len)
                 (if (xor (= f 1) parity)
                     (progn
                       (setf (aref buf head) c)
                       (decf head))
                     (progn
                       (setf (aref buf tail) c)
                       (incf tail))))))

  (if parity
      (loop repeat len
            for i downfrom (- tail 1)
            do (format t "~a" (aref buf (mod (+ i size) size))))
      (loop repeat len
            for i from (+ head 1)
            do (format t "~a" (aref buf (mod i size)))))
  (terpri))


(defun xor (a b) ;xor
  (not (equal a b)))
(let* ((n (read-line))
       (lst (loop :repeat (read) :collect (if (= 1 (read))
                                              (list 1 nil nil)
                                              (list 2 (read) (read-char)))))
       (reverse nil)
       (from-stack nil)
       (to-stack nil))
  (loop :for (x y z) :in lst
        :do (if (= x 1)
                (setf reverse (not reverse))
                (if (xor reverse (= 1 y))
                    (push z from-stack)
                    (push z to-stack))))
  (princ (if reverse
             (reverse (concatenate 'string from-stack n (reverse to-stack)))
             (concatenate 'string from-stack n (reverse to-stack)))))


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

;; BEGIN_INSERTED_CONTENTS
;; TODO: more efficient handling when modulus is (unsigned-byte 31) or
;; (unsigned-byte 32)
(declaim (inline mod-power))
(defun mod-power (base power modulus)
  "BASE := integer
POWER, MODULUS := non-negative fixnum"
  (declare ((integer 0 #.most-positive-fixnum) modulus power)
           (integer base))
  (labels ((recur (x p)
             (declare ((integer 0 #.most-positive-fixnum) x p)
                      #+sbcl (values (integer 0 #.most-positive-fixnum)))
             (cond ((zerop p) 1)
                   ((evenp p) (recur (mod (* x x) modulus) (ash p -1)))
                   (t (mod (* x (recur x (- p 1))) modulus)))))
    (recur (mod base modulus) power)))

;;;
;;; Modular arithmetic
;;;

;; Blankinship algorithm
;; Reference: https://topcoder-g-hatena-ne-jp.jag-icpc.org/spaghetti_source/20130126/ (Japanese)
(declaim (ftype (function * (values fixnum fixnum &optional)) %ext-gcd))
(defun %ext-gcd (a b)
  (declare (optimize (speed 3) (safety 0))
           (fixnum a b))
  (let ((y 1)
        (x 0)
        (u 1)
        (v 0))
    (declare (fixnum y x u v))
    (loop (when (zerop a)
            (return (values x y)))
          (let ((q (floor b a)))
            (decf x (the fixnum (* q u)))
            (rotatef x u)
            (decf y (the fixnum (* q v)))
            (rotatef y v)
            (decf b (the fixnum (* q a)))
            (rotatef b a)))))

;; Simple recursive version. A bit slower but more comprehensible.
;; https://cp-algorithms.com/algebra/extended-euclid-algorithm.html (English)
;; https://drken1215.hatenablog.com/entry/2018/06/08/210000 (Japanese)
;; (defun %ext-gcd (a b)
;;   (declare (optimize (speed 3) (safety 0))
;;            (fixnum a b))
;;   (if (zerop b)
;;       (values 1 0)
;;       (multiple-value-bind (p q) (floor a b) ; a = pb + q
;;         (multiple-value-bind (v u) (%ext-gcd b q)
;;           (declare (fixnum u v))
;;           (values u (the fixnum (- v (the fixnum (* p u)))))))))

;; TODO: deal with bignums
(declaim (inline ext-gcd))
(defun ext-gcd (a b)
  "Returns two integers X and Y which satisfy AX + BY = gcd(A, B)."
  (declare ((integer #.(- most-positive-fixnum) #.most-positive-fixnum) a b))
  (if (>= a 0)
      (if (>= b 0)
          (%ext-gcd a b)
          (multiple-value-bind (x y) (%ext-gcd a (- b))
            (declare (fixnum x y))
            (values x (- y))))
      (if (>= b 0)
          (multiple-value-bind (x y) (%ext-gcd (- a) b)
            (declare (fixnum x y))
            (values (- x) y))
          (multiple-value-bind (x y) (%ext-gcd (- a) (- b))
            (declare (fixnum x y))
            (values (- x) (- y))))))

(declaim (inline mod-inverse)
         (ftype (function * (values (mod #.most-positive-fixnum) &optional)) mod-inverse))

;; (defun mod-inverse (a modulus)
;;   "Solves ax ≡ 1 mod m. A and M must be coprime."
;;   (declare (integer a)
;;            ((integer 1 #.most-positive-fixnum) modulus))
;;   (mod (%ext-gcd (mod a modulus) modulus) modulus))

;; FIXME: Perhaps no advantage in efficiency? Then I should use the above simple
;; code.
(defun mod-inverse (a modulus)
  "Solves ax ≡ 1 mod m. A and M must be coprime."
  (declare ((integer 1 #.most-positive-fixnum) modulus))
  (let ((a (mod a modulus))
        (b modulus)
        (u 1)
        (v 0))
    (declare (fixnum a b u v))
    (loop until (zerop b)
          for quot = (floor a b)
          do (decf a (the fixnum (* quot b)))
             (rotatef a b)
             (decf u (the fixnum (* quot v)))
             (rotatef u v))
    (setq u (mod u modulus))
    (if (< u 0)
        (+ u modulus)
        u)))

(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 solve2 (n s)
  (let ((res 0))
    (dotimes (i n)
      (let ((d (aref s i)))
        (when (evenp d)
          (incf res (+ i 1)))))
    res))

(defun solve5 (n s)
  (let ((res 0))
    (dotimes (i n)
      (let ((d (aref s i)))
        (when (or (= d 0) (= d 5))
          (incf res (+ i 1)))))
    res))

(defun main ()
  (let* ((n (read))
         (p (read))
         (original-s (read-line))
         (s (make-array n :element-type 'uint8))
         (table (make-array p :element-type 'uint62 :initial-element 0))
         (powers (make-array (+ n 1) :element-type 'uint32 :initial-element 1)))
    (dotimes (i n)
      (setf (aref powers (+ i 1))
            (mod (* 10 (aref powers i)) p)))
    (dotimes (i n)
      (setf (aref s i) (- (char-code (aref original-s i)) 48)))
    (when (= p 2)
      (println (solve2 n s))
      (return-from main))
    (when (= p 5)
      (println (solve5 n s))
      (return-from main))
    (setf (aref table 0) 1)
    (let ((sum 0)
          (res 0))
      (loop for x from 1 to n
            for d = (aref s (- x 1))
            do (setq sum (mod (+ (* 10 sum) d) p))
               (let ((sum/10 (mod (* sum (mod-inverse (aref powers x) p)) p)))
                 (incf res (aref table sum/10))
                 (incf (aref table sum/10))))
      (println res))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4 3
3543
"
    "6
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4 2
2020
"
    "10
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "20 11
33883322005544116655
"
    "68
")))

Score : 500 points

Problem Statement

Takahashi has a string S of length N consisting of digits from 0 through 9.

He loves the prime number P. He wants to know how many non-empty (contiguous) substrings of S - there are N \times (N + 1) / 2 of them - are divisible by P when regarded as integers written in base ten.

Here substrings starting with a 0 also count, and substrings originated from different positions in S are distinguished, even if they are equal as strings or integers.

Compute this count to help Takahashi.

Constraints

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

S consists of digits.

|S| = N

2 \leq P \leq 10000

P is a prime number.

Input

Input is given from Standard Input in the following format:

N P
S

Output

Print the number of non-empty (contiguous) substrings of S that are divisible by P when regarded as an integer written in base ten.

Sample Input 1

4 3
3543

Sample Output 1

6

Here S = 3543. There are ten non-empty (contiguous) substrings of S:

3: divisible by 3.

35: not divisible by 3.

354: divisible by 3.

3543: divisible by 3.

5: not divisible by 3.

54: divisible by 3.

543: divisible by 3.

4: not divisible by 3.

43: not divisible by 3.

3: divisible by 3.

Six of these are divisible by 3, so print 6.

Sample Input 2

4 2
2020

Sample Output 2

10

Here S = 2020. There are ten non-empty (contiguous) substrings of S, all of which are divisible by 2, so print 10.

Note that substrings beginning with a 0 also count.

Sample Input 3

20 11
33883322005544116655

Sample Output 3

68