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

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

;;;
;;; Lowest common ancestor of tree (or forest) by binary lifting
;;; build: O(nlog(n))
;;; query: O(log(n))
;;;

;; PAY ATTENTION TO THE STACK SIZE! THE CONSTRUCTOR DOES DFS.

(deftype lca-vertex-number () '(signed-byte 32))

(defstruct (lca-table
            (:constructor %make-lca-table
                (size
                 &aux
                 ;; requires 1 + log_2{size-1}
                 (max-level (+ 1 (integer-length (- size 2))))
                 (depths (make-array size
                                     :element-type 'lca-vertex-number
                                     :initial-element -1))
                 (parents (make-array (list size max-level)
                                      :element-type 'lca-vertex-number))))
            (:conc-name lca-))
  (max-level nil :type (integer 0 #.most-positive-fixnum))
  (depths nil :type (simple-array lca-vertex-number (*)))
  (parents nil :type (simple-array lca-vertex-number (* *))))

(defun make-lca-table (graph &key root (key #'identity))
  "GRAPH := vector of adjacency lists
ROOT := null | non-negative fixnum

If ROOT is null, this function traverses each connected component of GRAPH from
an arbitrarily picked vertex. Otherwise this function traverses GRAPH only from
ROOT; GRAPH must be tree in the latter case."
  (declare (optimize (speed 3))
           (vector graph)
           (function key)
           ((or null (integer 0 #.most-positive-fixnum)) root))
  (let* ((size (length graph))
         (lca-table (%make-lca-table size))
         (depths (lca-depths lca-table))
         (parents (lca-parents lca-table))
         (max-level (lca-max-level lca-table)))
    (labels ((dfs (v prev-v depth)
               (declare (lca-vertex-number v prev-v))
               (setf (aref depths v) depth)
               (setf (aref parents v 0) prev-v)
               (dolist (node (aref graph v))
                 (let ((dest (funcall key node)))
                   (declare (lca-vertex-number dest))
                   (unless (= dest prev-v)
                     (dfs dest v (+ 1 depth)))))))
      (if root
          (dfs root -1 0)
          (dotimes (v size)
            (when (= (aref depths v) -1)
              (dfs v -1 0))))
      (dotimes (k (- max-level 1))
        (dotimes (v size)
          (if (= -1 (aref parents v k))
              (setf (aref parents v (+ k 1)) -1)
              (setf (aref parents v (+ k 1))
                    (aref parents (aref parents v k) k)))))
      lca-table)))

(define-condition two-vertices-disconnected-error (error)
  ((lca-table :initarg :lca-table :accessor two-vertices-disconnected-error-lca-table)
   (vertex1 :initarg :vertex1 :accessor two-vertices-disconnected-error-vertex1)
   (vertex2 :initarg :vertex2 :accessor two-vertices-disconnected-error-vertex2))
  (:report
   (lambda (c s)
     (format s "~W and ~W are disconnected on lca-table ~W"
             (two-vertices-disconnected-error-vertex1 c)
             (two-vertices-disconnected-error-vertex2 c)
             (two-vertices-disconnected-error-lca-table c)))))

(declaim (ftype (function * (values (integer 0 #.most-positive-fixnum) &optional))
                lca-get-lca))
(defun lca-get-lca (lca-table vertex1 vertex2)
  "Returns the lowest common ancestor of the vertices VERTEX1 and VERTEX2."
  (declare (optimize (speed 3))
           ((and lca-vertex-number (integer 0)) vertex1 vertex2))
  (let* ((u vertex1)
         (v vertex2)
         (depths (lca-depths lca-table))
         (parents (lca-parents lca-table))
         (max-level (lca-max-level lca-table)))
    (declare (lca-vertex-number u v))
    ;; Ensures depth[u] <= depth[v]
    (when (> (aref depths u) (aref depths v))
      (rotatef u v))
    (dotimes (k max-level)
      (when (logbitp k (- (aref depths v) (aref depths u)))
        (setf v (aref parents v k))))
    (if (= u v)
        u
        (loop for k from (- max-level 1) downto 0
              unless (= (aref parents u k) (aref parents v k))
              do (setq u (aref parents u k)
                       v (aref parents v k))
              finally (if (= (aref parents u 0) -1)
                          (error 'two-vertices-disconnected-error
                                 :lca-table lca-table
                                 :vertex1 vertex1
                                 :vertex2 vertex2)
                          (return (aref parents u 0)))))))

(declaim (inline lca-distance))
(defun lca-distance (lca-table u v)
  "Returns the distance between two vertices U and V."
  (declare (optimize (speed 3)))
  (let ((depths (lca-depths lca-table))
        (lca (lca-get-lca lca-table u v)))
    (+ (- (aref depths u) (aref depths lca))
       (- (aref depths v) (aref depths lca)))))

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

;; TODO:
;; - more sane handling of unbounded index
;; - handy function for initialization
;; - iteration; map
;; - abstraction
;; - printer

(defconstant +persistent-vector-log+ 16)

(declaim (inline %make-persistent-vector))
(defstruct (persistent-vector (:constructor %make-persistent-vector ())
                              (:conc-name %pv-))
  (value 0 :type fixnum)
  (children nil :type (or null (simple-vector #.+persistent-vector-log+))))

(defun pv-assoc (pvector index value)
  (declare ((or null persistent-vector) pvector)
           ((integer 0 #.most-positive-fixnum) index))
  (labels ((recur (pvector index)
             (declare ((or (integer 0 0) persistent-vector) pvector)
                      ((integer 0 #.most-positive-fixnum) index))
             (let ((res (%make-persistent-vector)))
               (if (eql 0 pvector)
                   (setf (%pv-children res)
                         (make-array +persistent-vector-log+ :initial-element 0))
                   (setf (%pv-children res) (copy-seq (%pv-children pvector))
                         (%pv-value res) (%pv-value pvector)))
               (if (zerop index)
                   (setf (%pv-value res) value)
                   (setf (aref (%pv-children res) (mod index +persistent-vector-log+))
                         (recur (aref (%pv-children res) (mod index +persistent-vector-log+))
                                (floor index +persistent-vector-log+))))
               res)))
    (recur (or pvector 0) index)))

(defun pv-ref (pvector index)
  (declare ((or null persistent-vector) pvector))
  (labels ((recur (pvector index)
             (declare ((or (integer 0 0) persistent-vector) pvector)
                      ((integer 0 #.most-positive-fixnum) index))
             (cond ((eql 0 pvector) 0)
                   ((zerop index) (%pv-value pvector))
                   (t (recur (aref (%pv-children pvector) (mod index +persistent-vector-log+))
                             (floor index +persistent-vector-log+))))))
    (recur (or pvector 0) index)))

(defun main ()
  (let* ((n (read))
         (q (read))
         (graph (make-array n :element-type 'list :initial-element nil))
         (wgraph (make-array n :element-type 'list :initial-element nil)))
    (dotimes (i (- n 1))
      (let ((a (- (read-fixnum) 1))
            (b (- (read-fixnum) 1))
            (c (- (read-fixnum) 1))
            (d (read-fixnum)))
        (push a (aref graph b))
        (push b (aref graph a))
        (push (list* a c d) (aref wgraph b))
        (push (list* b c d) (aref wgraph a))))
    (let ((lca-table (make-lca-table graph))
          (dists (make-array n :element-type 'uint32))
          (ccounts (make-array n :initial-element nil))
          (cdists (make-array n :initial-element nil)))
      (sb-int:named-let dfs ((v 0) (parent -1))
        (dolist (node (aref wgraph v))
          (destructuring-bind (child color . cost) node
            (unless (= child parent)
              (setf (aref dists child) (+ (aref dists v) cost))
              (setf (aref ccounts child)
                    (pv-assoc (aref ccounts v)
                              color
                              (+ 1 (pv-ref (aref ccounts v) color))))
              (setf (aref cdists child)
                    (pv-assoc (aref cdists v)
                              color
                              (+ cost (pv-ref (aref cdists v) color))))
              (dfs child v)))))
      (with-buffered-stdout
        (dotimes (_ q)
          (let* ((x (- (read-fixnum) 1))
                 (y (read-fixnum))
                 (u (- (read-fixnum) 1))
                 (v (- (read-fixnum) 1))
                 (lca (lca-get-lca lca-table u v))
                 (base (+ (aref dists u) (aref dists v) (* -2 (aref dists lca))))
                 (ccount (+ (pv-ref (aref ccounts u) x)
                            (pv-ref (aref ccounts v) x)
                            (* -2 (pv-ref (aref ccounts lca) x))))
                 (cdist (+ (pv-ref (aref cdists u) x)
                           (pv-ref (aref cdists v) x)
                           (* -2 (pv-ref (aref cdists lca) x)))))
            (dbg x y u v lca)
            (dbg base ccount cdist)
            (println (+ (- base cdist) (* ccount y)))))))))

#-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 "5 3
1 2 1 10
1 3 2 20
2 4 4 30
5 2 1 40
1 100 1 4
1 100 1 5
3 1000 3 4
"
    "130
200
60
")))


(defmacro defsolver (name vars &body body)
  `(defun ,name ()
     (let (,@(mapcar #'list
            vars
            (mapcar (constantly '(read))
                vars)))
       ,@body)))

(defsolver solution-aaa ()
  (let ((l))
    (dotimes (i 4)
      (let* ((c (read-char))
	     (old (rassoc c l :test #'char=)))
	(push (cons (if old (1+ (car old)) 1)
		    c)
	      l)))
    (format t "~:[No~;Yes~]"
	    (= 2 (apply #'max
		   (mapcar #'car l))))))

(solution-aaa)

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

Score : 100 points

Problem Statement

You are given a 4-character string S consisting of uppercase English letters.
Determine if S consists of exactly two kinds of characters which both appear twice in S.

Constraints

The length of S is 4.

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S consists of exactly two kinds of characters which both appear twice in S, print Yes; otherwise, print No.

Sample Input 1

ASSA

Sample Output 1

Yes

S consists of A and S which both appear twice in S.

Sample Input 2

STOP

Sample Output 2

No

Sample Input 3

FFEE

Sample Output 3

Yes

Sample Input 4

FREE

Sample Output 4

No

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.


(defmacro defsolver (name vars &body body)
  `(defun ,name ()
     (let (,@(mapcar #'list
            vars
            (mapcar (constantly '(read))
                vars)))
       ,@body)))

(defsolver solution-a ()
  (let* ((l (loop repeat 4 collect
		 (read-char))))
    (format t "~:[No~;Yes~]"
	    (or
	     (and
	      (eql (nth 0 l) (nth 1 l))
	      (eql (nth 2 l) (nth 3 l)))
	     (and
	      (eql (nth 0 l) (nth 2 l))
	      (eql (nth 1 l) (nth 3 l)))
	     (and
	      (eql (nth 0 l) (nth 3 l))
	      (eql (nth 1 l) (nth 2 l)))))))

(solution-a)


(defun readseq (num)
  (loop
    as i
    below num
    collect (read)
  )
)

(defun ismonoinc (l)
  (or
    (< (first l) (second l) (third l))
    (> (first l) (second l) (third l))
  )
)

(defun createordinaryseq (n seq)
  (loop
    as i below (- n 2)
    collect (ismonoinc (list (first seq) (second seq) (third seq)))
    do (setq seq (cdr seq))
  )
)

(let* (
    (n (read))
    (seq (readseq n))
  )
  (princ (count T (createordinaryseq n seq)))
)

Score : 200 points

Problem Statement

We have a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n}.

Print the number of elements p_i (1 < i < n) that satisfy the following condition:

p_i is the second smallest number among the three numbers p_{i - 1}, p_i, and p_{i + 1}.

Constraints

All values in input are integers.

3 \leq n \leq 20

p is a permutation of {1,\ 2,\ ...,\ n}.

Input

Input is given from Standard Input in the following format:

n
p_1 p_2 ... p_n

Output

Print the number of elements p_i (1 < i < n) that satisfy the condition.

Sample Input 1

5
1 3 5 4 2

Sample Output 1

2

p_2 = 3 is the second smallest number among p_1 = 1, p_2 = 3, and p_3 = 5. Also, p_4 = 4 is the second smallest number among p_3 = 5, p_4 = 4, and p_5 = 2. These two elements satisfy the condition.

Sample Input 2

9
9 6 3 2 5 8 7 4 1

Sample Output 2

5


;; -*- 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))
                 (shadow :run)
                 (use-package :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)

;; 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))
         (ds (make-array n :element-type 'uint32)))
    (dotimes (i n) (setf (aref ds i) (read-fixnum)))
    (setf ds (sort ds #'<))
    (let* ((mid2 (floor n 2))
           (mid1 (- mid2 1)))
      (println (- (aref ds mid2) (aref ds mid1))))))

#-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 "6
9 1 4 4 6 7
"
    "2
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "8
9 1 14 5 5 4 4 14
"
    "0
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "14
99592 10342 29105 78532 83018 11639 92015 77204 30914 21912 34519 80835 100000 1
"
    "42685
")))

Score : 300 points

Problem Statement

Takahashi made N problems for competitive programming.
The problems are numbered 1 to N, and the difficulty of Problem i is represented as an integer d_i (the higher, the harder).

He is dividing the problems into two categories by choosing an integer K, as follows:

A problem with difficulty K or higher will be for ARCs.

A problem with difficulty lower than K will be for ABCs.

How many choices of the integer K make the number of problems for ARCs and the number of problems for ABCs the same?

Problem Statement

2 \leq N \leq 10^5

N is an even number.

1 \leq d_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
d_1 d_2 ... d_N

Output

Print the number of choices of the integer K that make the number of problems for ARCs and the number of problems for ABCs the same.

Sample Input 1

6
9 1 4 4 6 7

Sample Output 1

2

If we choose K=5 or 6, Problem 1, 5, and 6 will be for ARCs, Problem 2, 3, and 4 will be for ABCs, and the objective is achieved.
Thus, the answer is 2.

Sample Input 2

8
9 1 14 5 5 4 4 14

Sample Output 2

0

There may be no choice of the integer K that make the number of problems for ARCs and the number of problems for ABCs the same.

Sample Input 3

14
99592 10342 29105 78532 83018 11639 92015 77204 30914 21912 34519 80835 100000 1

Sample Output 3

42685


(defmacro defsolver (name vars &body body)
  `(defun ,name ()
     (let (,@(mapcar #'list
            vars
            (mapcar (constantly '(read))
                vars)))
       ,@body)))

(let ((arr (make-array (list 2000 2000) :initial-element -1)))
  (defun comb (n k)
    (when (< (aref arr n k) 0)
      (setf
       (aref arr n k)
       (cond
	 ((< n k) 0)
	 ((= n k) 1)
	 ((= k 0) 1)
	 ((= k 1) n)
	 (t (+ (comb (1- n) k)
	       (comb (1- n) (1- k)))))))
    (aref arr n k)))

(defsolver solution-d (n k)
  (loop for i from 1 to k do
    (let ((cnt (comb
		(+ n (- k) 1)
		i))
	  (w (comb (1- k) (1- i))))
      (format t "~a~%"
	    (mod
	     (* cnt w)
	     1000000007)))))

(solution-d)

Score : 400 points

Problem Statement

There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.

First, Snuke will arrange the N balls in a row from left to right.

Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible.

How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.

Constraints

1 \leq K \leq N \leq 2000

Input

Input is given from Standard Input in the following format:

N K

Output

Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7.

Sample Input 1

5 3

Sample Output 1

3
6
1

There are three ways to arrange the balls so that Takahashi will need exactly one move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B stands for red and blue, respectively).

There are six ways to arrange the balls so that Takahashi will need exactly two moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B), (B, R, B, B, R), and (B, R, R, B, B).

There is one way to arrange the balls so that Takahashi will need exactly three moves: (B, R, B, R, B).

Sample Input 2

2000 3

Sample Output 2

1998
3990006
327341989

Be sure to print the numbers of arrangements modulo 10^9+7.


(defmacro defsolver (name vars &body body)
  `(defun ,name ()
     (let (,@(mapcar #'list
            vars
            (mapcar (constantly '(read))
                vars)))
       ,@body)))

(let ((arr (make-array (list 2000 50) :initial-element -1)))
  (defun comb (n k)
    (when (< (aref arr n k) 0)
      (setf
       (aref arr n k)
       (cond
	 ((= n 0) 0)
	 ((= k 0) 1)
	 ((= k 1) n)
	 (t (+ (comb (1- n) k)
	       (comb (1- n) (1- k)))))))
    (aref arr n k)))

(defsolver solution-d (n k)
  (dotimes (i k)
    (let ((cnt (comb
		(+ n (- k) 1)
		(1+ i)))
	  (w (if (< 0 i (1- k))
		 (1- k)
		 1)))
      (format t "~a~%"
	    (mod
	     (* cnt w)
	     1000000007)))))

(solution-d)


(defparameter seq (read-line))

(defun check (text)
  (if (or (eq (char text 0)
              (char text 1))
          (eq (char text 1)
              (char text 2))
          (eq (char text 2)
              (char text 3)))
      "Bad"
      "Good"))

(print (check seq))

Score : 100 points

Problem Statement

The door of Snuke's laboratory is locked with a security code.

The security code is a 4-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same.

You are given the current security code S. If S is hard to enter, print Bad; otherwise, print Good.

Constraints

S is a 4-character string consisting of digits.

Input

Input is given from Standard Input in the following format:

S

Output

If S is hard to enter, print Bad; otherwise, print Good.

Sample Input 1

3776

Sample Output 1

Bad

The second and third digits are the same, so 3776 is hard to enter.

Sample Input 2

8080

Sample Output 2

Good

There are no two consecutive digits that are the same, so 8080 is not hard to enter.

Sample Input 3

1333

Sample Output 3

Bad

Sample Input 4

0024

Sample Output 4

Bad


(defparameter seq (subseq (read-line) 0 4)

(defun check (text)
  (if (or (eq (char text 0)
              (char text 1))
          (eq (char text 1)
              (char text 2))
          (eq (char text 2)
              (char text 3)))
      "Bad"
      "Good")))

(print (check seq))


(defun check (text)
  (if (= 1 (length text))
      "Good"
      (if (equal (char text 0)
                 (char text 1))
          "Bad"
          (check (subseq text 1)))))

(defparameter line (read-line nil nil))

(print (check line))


(let* ((line (read-line nil nil)))
  (if (or (and (char= (char line 0) (char line 1)))
		  (and (char= (char line 1) (char line 2)))
		  (and (char= (char line 2) (char line 3))))
	(format t "Bad")
	(format t "Good")))


(defmacro defsolver (name vars &body body)
  `(defun ,name ()
     (let (,@(mapcar #'list
            vars
            (mapcar (constantly '(read))
                vars)))
       ,@body)))

(defsolver solution-b (n l)
  (let ((sum (* (/ (+ (* 2 l) n -1) 2) n)))
    (format t "~a~%"
     (cond
	 ((<= (- 1 N) l 0) sum)
	 ((< l 0) (- sum l n -1))
	 (t (- sum l))))))

(solution-b)

Score : 200 points

Problem Statement

You have N apples, called Apple 1, Apple 2, Apple 3, ..., Apple N. The flavor of Apple i is L+i-1, which can be negative.

You can make an apple pie using one or more of the apples. The flavor of the apple pie will be the sum of the flavors of the apples used.

You planned to make an apple pie using all of the apples, but being hungry tempts you to eat one of them, which can no longer be used to make the apple pie.

You want to make an apple pie that is as similar as possible to the one that you planned to make. Thus, you will choose the apple to eat so that the flavor of the apple pie made of the remaining N-1 apples will have the smallest possible absolute difference from the flavor of the apple pie made of all the N apples.

Find the flavor of the apple pie made of the remaining N-1 apples when you choose the apple to eat as above.

We can prove that this value is uniquely determined.

Constraints

2 \leq N \leq 200

-100 \leq L \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N L

Output

Find the flavor of the apple pie made of the remaining N-1 apples when you optimally choose the apple to eat.

Sample Input 1

5 2

Sample Output 1

18

The flavors of Apple 1, 2, 3, 4, and 5 are 2, 3, 4, 5, and 6, respectively. The optimal choice is to eat Apple 1, so the answer is 3+4+5+6=18.

Sample Input 2

3 -1

Sample Output 2

0

The flavors of Apple 1, 2, and 3 are -1, 0, and 1, respectively. The optimal choice is to eat Apple 2, so the answer is (-1)+1=0.

Sample Input 3

30 -50

Sample Output 3

-1044


;; -*- 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))
                 (shadow :run)
                 (use-package :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)

;; 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* ((n (read))
         (l (read)))
    (labels ((frob (i) (+ l i -1)))
      (let* ((original (loop for i from 1 to n sum (frob i)))
             (res #xffffffff))
        (loop for excluded from 1 to n
              for value = (loop for i from 1 to n unless (= i excluded) sum (frob i))
              when (<= (abs (- value original))
                       (abs (- res original)))
              do (setf res value))
        (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)))


;m以上n以下でNの倍数の個数を数える
(defun count-m (m n k)
  (-(floor n k)
    (floor (1- m) k)))

(defun solve (A B C D)
  (let  (( E (lcm C D)))
    (- (1+ (- B A))
       (- (+ (count-m A B C)
	     (count-m A B D))
	  (count-m A B E)))))

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

Score : 300 points

Problem Statement

You are given four integers A, B, C, and D. Find the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Constraints

1\leq A\leq B\leq 10^{18}

1\leq C,D\leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Sample Input 1

4 9 2 3

Sample Output 1

2

5 and 7 satisfy the condition.

Sample Input 2

10 40 6 8

Sample Output 2

23

Sample Input 3

314159265358979323 846264338327950288 419716939 937510582

Sample Output 3

532105071133627368


(let ((n (read))
      (end 2000000000)
      (lst (make-array 0 :element-type 'list
                         :adjustable t
                         :fill-pointer 0))
      s-lst)
  (dotimes (i n)
    (vector-push-extend (list (read) (read)) lst))
  (setf s-lst (sort lst #'(lambda (x y) (> (second x) (second y)))))
  (loop for i across s-lst do
        (if (< (second i) end) (setf end (second i)))
        (decf end (first i)))
  (princ (if (< end 0) "No" "Yes")))

Score: 400 points

Problem Statement

Kizahashi, who was appointed as the administrator of ABC at National Problem Workshop in the Kingdom of AtCoder, got too excited and took on too many jobs.

Let the current time be time 0. Kizahashi has N jobs numbered 1 to N.

It takes A_i units of time for Kizahashi to complete Job i. The deadline for Job i is time B_i, and he must complete the job before or at this time.

Kizahashi cannot work on two or more jobs simultaneously, but when he completes a job, he can start working on another immediately.

Can Kizahashi complete all the jobs in time? If he can, print Yes; if he cannot, print No.

Constraints

All values in input are integers.

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

1 \leq A_i, B_i \leq 10^9 (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
.
.
.
A_N B_N

Output

If Kizahashi can complete all the jobs in time, print Yes; if he cannot, print No.

Sample Input 1

5
2 4
1 9
1 8
4 9
3 12

Sample Output 1

Yes

He can complete all the jobs in time by, for example, doing them in the following order:

Do Job 2 from time 0 to 1.

Do Job 1 from time 1 to 3.

Do Job 4 from time 3 to 7.

Do Job 3 from time 7 to 8.

Do Job 5 from time 8 to 11.

Note that it is fine to complete Job 3 exactly at the deadline, time 8.

Sample Input 2

3
334 1000
334 1000
334 1000

Sample Output 2

No

He cannot complete all the jobs in time, no matter what order he does them in.

Sample Input 3

30
384 8895
1725 9791
170 1024
4 11105
2 6
578 1815
702 3352
143 5141
1420 6980
24 1602
849 999
76 7586
85 5570
444 4991
719 11090
470 10708
1137 4547
455 9003
110 9901
15 8578
368 3692
104 1286
3 4
366 12143
7 6649
610 2374
152 7324
4 7042
292 11386
334 5720

Sample Output 3

Yes


(defmacro defsolver (name vars &body body)
  `(defun ,name ()
     (let (,@(mapcar #'list
            vars
            (mapcar (constantly '(read))
                vars)))
       ,@body)))

(defsolver solution-d (n)
  (let ((l (loop for i below n collect (cons (read) (read))))
        (acc 0))
    (sort l #'< :key #'cdr)
    (format t "~:[No~;Yes~]"
            (every #'(lambda (task)
                   (incf acc (car task))
                   (<= acc (cdr task)))
                   l))))

(solution-d)


(if (< (read) (read))
    (format t "0~%")
    (format t "10~%"))

Score : 100 points

Problem Statement

X and A are integers between 0 and 9 (inclusive).

If X is less than A, print 0; if X is not less than A, print 10.

Constraints

0 \leq X, A \leq 9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X A

Output

If X is less than A, print 0; if X is not less than A, print 10.

Sample Input 1

3 5

Sample Output 1

0

3 is less than 5, so we should print 0.

Sample Input 2

7 5

Sample Output 2

10

7 is not less than 5, so we should print 10.

Sample Input 3

6 6

Sample Output 3

10

6 is not less than 6, so we should print 10.


(defun split (str)
  (labels ((inner (rest-str-list stack-str-list temp-out)
                  (if rest-str-list
                      (let ((now-char (car rest-str-list)))
                        (cond ((eq #\space now-char) (inner (cdr rest-str-list)
                                                            '()
                                                            (cons (concatenate 'string (reverse stack-str-list))
                                                                  temp-out)))
                              (t (inner (cdr rest-str-list)
                                        (cons now-char stack-str-list)
                                        temp-out))))
                      (reverse (cons (concatenate 'string (reverse stack-str-list))
                                     temp-out)))))
          (inner (concatenate 'list str)
                 '()
                 '())))

(defun input-to-list (str)
  (mapcar #'parse-integer (split str)))

(defvar xa (input-to-list (read-line)))
(format t "~d"
        (if (< x a)
            0
            10))


;;; Utils

(defmacro read-numbers-to-list (size)
  `(progn
     (when (not (integerp ,size))
       (error "Size must be integer."))
     (when (< ,size 0)
       (error "Size must be plus or zero."))
     (loop repeat ,size collect (read))))

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

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

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

(defmethod make-cumlative-sum ((sequence array))
  (declare (type (simple-array fixnum) sequence))
  (the array
       (let* ((n (length sequence))
              (acc (make-array (1+ n) :element-type 'integer :initial-element 0)))
         (loop for i below n do
              (setf (aref acc (1+ i)) (+ (aref sequence i)
                                         (aref acc i)))
            finally
              (return acc)))))

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

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

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

;;; Write code here

(defun solve (n x l)
  (let ((cum (make-cumlative-sum l)))
    (length (remove-if-not
             (lambda (pos)
               (<= pos x))
             cum))))

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

(main)

Score : 200 points

Problem Statement

A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}.

How many times will the ball make a bounce where the coordinate is at most X?

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 100

1 \leq X \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
L_1 L_2 ... L_{N-1} L_N

Output

Print the number of times the ball will make a bounce where the coordinate is at most X.

Sample Input 1

3 6
3 4 5

Sample Output 1

2

The ball will make a bounce at the coordinates 0, 3, 7 and 12, among which two are less than or equal to 6.

Sample Input 2

4 9
3 3 3 3

Sample Output 2

4

The ball will make a bounce at the coordinates 0, 3, 6, 9 and 12, among which four are less than or equal to 9.


(defun rec (acc lst x i)
  (if (<= acc x)
	(rec (+ acc (car lst)) (cdr lst) x (1+ i))
	(1- i)))
(defun splitat (c line)
  (labels ((rec (line acc)
				(let ((pos (position-if (lambda(cc) (char= c cc)) line)))
				  (if pos
					  (rec (subseq line (1+ pos)) (cons (subseq line 0 pos) acc))
					(nreverse (cons line acc))))))
	(rec line nil)))
(let* ((line0 (read-line nil nil))
	   (splited0 (mapcar #'parse-integer (splitat #\space line0)))
	   (line1 (read-line nil nil))
	   (splited1 (mapcar #'parse-integer (splitat #\space line1)))
	   )
  (format t "~A~%" (rec 0 splited1 (cadr splited0) 1)))


Score : 300 points

Problem Statement

There is a rectangle in a coordinate plane. The coordinates of the four vertices are (0,0), (W,0), (W,H), and (0,H).
You are given a point (x,y) which is within the rectangle or on its border. We will draw a straight line passing through (x,y) to cut the rectangle into two parts. Find the maximum possible area of the part whose area is not larger than that of the other. Additionally, determine if there are multiple ways to cut the rectangle and achieve that maximum.

Constraints

1 \leq W,H \leq 10^9

0\leq x\leq W

0\leq y\leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

W H x y

Output

Print the maximum possible area of the part whose area is not larger than that of the other, followed by 1 if there are multiple ways to cut the rectangle and achieve that maximum, and 0 otherwise.

The area printed will be judged correct when its absolute or relative error is at most 10^{-9}.

Sample Input 1

2 3 1 2

Sample Output 1

3.000000 0

The line x=1 gives the optimal cut, and no other line does.

Sample Input 2

2 2 1 1

Sample Output 2

2.000000 1


;;; Utils (quoted from https://competitive12.blogspot.com/2020/03/common-lisp.html)

;; Read fixnum

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

;; fast read-line

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

;;; invoke child process

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

;-------------------
; Write code here
;-------------------

(defun solve (w h x y)
  (if (and (= (* x 2) w)
          (= (* y 2) h))
      (cons (coerce (/ (* w h) 2) 'double-float) 1)
      (cons (coerce (/ (* w h) 2) 'double-float) 0)))

(defun main ()
   (let ((l (read-from-string (concatenate 'string "(" (read-line) ")"))))
     (destructuring-bind (w h x y) l
       (setq ans (solve w h x y))
       (let ((*read-default-float-format* 'double-float))
         (format t "~a ~a" (first ans) (rest ans)))
       (fresh-line))))

(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))
                 (shadow :run)
                 (use-package :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)

;; BEGIN_INSERTED_CONTENTS
(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (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 #\-))
                                  (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
(declaim (inline bitree-update!))
(defun bitree-update! (bitree index1 index2 delta)
  "destructively increments the array: array[index1][index2] += delta."
  (declare ((integer 0 #.most-positive-fixnum) index1 index2))
  (let ((length1 (array-dimension bitree 0))
        (length2 (array-dimension bitree 1)))
    (do ((i index1 (logior i (+ i 1))))
        ((>= i length1))
      (declare (fixnum i))
      (let ((base-i (array-row-major-index bitree i 0)))
        (declare (fixnum base-i))
        (do ((j index2 (logior j (+ j 1))))
            ((>= j length2))
          (declare (fixnum j))
          (setf (row-major-aref bitree (+ base-i j))
                (funcall (lambda (x y) (mod (+ x y) +mod+))
                         (row-major-aref bitree (the fixnum (+ base-i j)))
                         delta)))))
    bitree))

(declaim (inline bitree-sum))
(defun bitree-sum (bitree end1 end2)
  "returns the sum of the rectangle region: array[0][0] + ... +
array[end1-1][end2-1]."
  (declare ((integer 0 #.most-positive-fixnum) end1 end2))
  (let ((res 0))
    (declare (type uint62 res))
    (do ((i (- end1 1) (- (logand i (+ i 1)) 1)))
        ((< i 0))
      (declare (fixnum i))
      (let ((base-i (array-row-major-index bitree i 0)))
        (declare (fixnum base-i))
        (do ((j (- end2 1) (- (logand j (+ j 1)) 1)))
            ((< j 0))
          (declare (fixnum j))
          (incf res (row-major-aref bitree (the fixnum (+ base-i j)))))))
    (mod res +mod+)))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (m (read))
         (ss (make-array n :element-type 'uint32))
         (ts (make-array m :element-type 'uint32))
         (bitree (make-array '(2000 2000) :element-type 'uint32 :initial-element 0)))
    (declare (uint16 n m))
    (dotimes (i n) (setf (aref ss i) (read-fixnum)))
    (dotimes (i m) (setf (aref ts i) (read-fixnum)))
    (dotimes (i n)
      (dotimes (j m)
        (when (= (aref ss i) (aref ts j))
          (bitree-update! bitree i j (+ 1 (bitree-sum bitree i j))))))
    (println (mod (+ 1 (bitree-sum bitree n m)) +mod+))))

#-swank(main)

Score : 500 points

Problem Statement

You are given two integer sequences S and T of length N and M, respectively, both consisting of integers between 1 and 10^5 (inclusive).

In how many pairs of a subsequence of S and a subsequence of T do the two subsequences are the same in content?

Here the subsequence of A is a sequence obtained by removing zero or more elements from A and concatenating the remaining elements without changing the order.

For both S and T, we distinguish two subsequences if the sets of the indices of the removed elements are different, even if the subsequences are the same in content.

Since the answer can be tremendous, print the number modulo 10^9+7.

Constraints

1 \leq N, M \leq 2 \times 10^3

The length of S is N.

The length of T is M.

1 \leq S_i, T_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
S_1 S_2 ... S_{N-1} S_{N}
T_1 T_2 ... T_{M-1} T_{M}

Output

Print the number of pairs of a subsequence of S and a subsequence of T such that the subsequences are the same in content, modulo 10^9+7.

Sample Input 1

2 2
1 3
3 1

Sample Output 1

3

S has four subsequences: (), (1), (3), (1, 3).

T has four subsequences: (), (3), (1), (3, 1).

There are 1 \times 1 pair of subsequences in which the subsequences are both (), 1 \times 1 pair of subsequences in which the subsequences are both (1), and 1 \times 1 pair of subsequences in which the subsequences are both (3), for a total of three pairs.

Sample Input 2

2 2
1 1
1 1

Sample Output 2

6

S has four subsequences: (), (1), (1), (1, 1).

T has four subsequences: (), (1), (1), (1, 1).

There are 1 \times 1 pair of subsequences in which the subsequences are both (), 2 \times 2 pairs of subsequences in which the subsequences are both (1), and 1 \times 1 pair of subsequences in which the subsequences are both (1,1), for a total of six pairs.
Note again that we distinguish two subsequences if the sets of the indices of the removed elements are different, even if the subsequences are the same in content.

Sample Input 3

4 4
3 4 5 6
3 4 5 6

Sample Output 3

16

Sample Input 4

10 9
9 6 5 7 5 9 8 5 6 7
8 6 8 5 5 7 9 9 7

Sample Output 4

191

Sample Input 5

20 20
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

Sample Output 5

846527861

Be sure to print the number modulo 10^9+7.


;; -*- 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))
                 (shadow :run)
                 (use-package :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)

;; BEGIN_INSERTED_CONTENTS
(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (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 #\-))
                                  (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
(declaim (inline bitree-update!))
(defun bitree-update! (bitree index1 index2 delta)
  "destructively increments the array: array[index1][index2] += delta."
  (declare ((integer 0 #.most-positive-fixnum) index1 index2))
  (let ((length1 (array-dimension bitree 0))
        (length2 (array-dimension bitree 1)))
    (do ((i index1 (logior i (+ i 1))))
        ((>= i length1))
      (declare ((integer 0 #.most-positive-fixnum) i))
      (let ((base-i (array-row-major-index bitree i 0)))
        (declare ((integer 0 #.most-positive-fixnum) base-i))
        (do ((j index2 (logior j (+ j 1))))
            ((>= j length2))
          (declare ((integer -1 #.most-positive-fixnum) j))
          (setf (row-major-aref bitree (+ base-i j))
                (funcall (lambda (x y) (mod (+ x y) +mod+))
                         (row-major-aref bitree (+ base-i j))
                         delta)))))
    bitree))

(declaim (inline bitree-sum))
(defun bitree-sum (bitree end1 end2)
  "returns the sum of the rectangle region: array[0][0] + ... +
array[end1-1][end2-1]."
  (declare ((integer 0 #.most-positive-fixnum) end1 end2))
  (let ((res 0))
    (declare (type uint62 res))
    (do ((i (- end1 1) (- (logand i (+ i 1)) 1)))
        ((< i 0))
      (declare ((integer -1 4611686018427387903) i))
      (let ((base-i (array-row-major-index bitree i 0)))
        (declare ((integer 0 #.most-positive-fixnum) base-i))
        (do ((j (- end2 1) (- (logand j (+ j 1)) 1)))
            ((< j 0))
          (declare ((integer -1 #.most-positive-fixnum) j))
          (incf res (row-major-aref bitree (the (integer -1 #.most-positive-fixnum) (+ base-i j)))))))
    (mod res +mod+)))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (m (read))
         (ss (make-array n :element-type 'uint32))
         (ts (make-array m :element-type 'uint32))
         (bitree (make-array '(2000 2000) :element-type 'uint32 :initial-element 0)))
    (declare (uint16 n m))
    (dotimes (i n) (setf (aref ss i) (read-fixnum)))
    (dotimes (i m) (setf (aref ts i) (read-fixnum)))
    (dotimes (i n)
      (dotimes (j m)
        (when (= (aref ss i) (aref ts j))
          (bitree-update! bitree i j (+ 1 (bitree-sum bitree i j))))))
    (println (mod (+ 1 (bitree-sum bitree n m)) +mod+))))

#-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))
                 (shadow :run)
                 (use-package :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)

;; BEGIN_INSERTED_CONTENTS
(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (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 #\-))
                                  (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
(declaim (inline bitree-update!))
(defun bitree-update! (bitree index1 index2 delta)
  "destructively increments the array: array[index1][index2] += delta."
  (let ((length1 (array-dimension bitree 0))
        (length2 (array-dimension bitree 1)))
    (do ((i index1 (logior i (+ i 1))))
        ((>= i length1))
      (declare ((integer 0 4611686018427387903) i))
      (do ((j index2 (logior j (+ j 1))))
          ((>= j length2))
        (setf (aref bitree i j)
              (funcall (lambda (x y) (mod (+ x y) +mod+)) (aref bitree i j)
                       delta))))
    bitree))

(declaim (inline bitree-sum))
(defun bitree-sum (bitree end1 end2)
  "returns the sum of the rectangle region: array[0][0] + ... +
array[end1-1][end2-1]."
  (declare ((integer 0 4611686018427387903) end1 end2))
  (let ((res 0))
    (declare (type uint62 res))
    (do ((i (- end1 1) (- (logand i (+ i 1)) 1)))
        ((< i 0))
      (declare ((integer -1 4611686018427387903) i))
      (do ((j (- end2 1) (- (logand j (+ j 1)) 1)))
          ((< j 0))
        (incf res (aref bitree i j))))
    (mod res +mod+)))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (m (read))
         (ss (make-array n :element-type 'uint32))
         (ts (make-array m :element-type 'uint32))
         (bitree (make-array '(2000 2000) :element-type 'uint32 :initial-element 0)))
    (declare (uint16 n m))
    (dotimes (i n) (setf (aref ss i) (read-fixnum)))
    (dotimes (i m) (setf (aref ts i) (read-fixnum)))
    (dotimes (i n)
      (dotimes (j m)
        (when (= (aref ss i) (aref ts j))
          (bitree-update! bitree i j (+ 1 (bitree-sum bitree i j))))))
    (println (mod (+ 1 (bitree-sum bitree n m)) +mod+))))

#-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))
                 (shadow :run)
                 (use-package :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)

;; 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))
         (xs- (make-array 0 :fill-pointer 0 :element-type 'int32))
         (xs0 (make-array 0 :fill-pointer 0 :element-type 'int32))
         (xs+ (make-array 0 :fill-pointer 0 :element-type 'int32))
         (ys- (make-array 0 :fill-pointer 0 :element-type 'int32))
         (ys0 (make-array 0 :fill-pointer 0 :element-type 'int32))
         (ys+ (make-array 0 :fill-pointer 0 :element-type 'int32)))
    (dotimes (i n)
      (let ((x (read-fixnum))
            (y (read-fixnum))
            (d (read-char)))
        (case d
          (#\R
           (vector-push-extend x xs+)
           (vector-push-extend y ys0))
          (#\L
           (vector-push-extend x xs-)
           (vector-push-extend y ys0))
          (#\U
           (vector-push-extend x xs0)
           (vector-push-extend y ys+))
          (#\D
           (vector-push-extend x xs0)
           (vector-push-extend y ys-)))))
    (let ((xmax+ (reduce #'max xs+ :initial-value most-negative-fixnum))
          (xmax- (reduce #'max xs- :initial-value most-negative-fixnum))
          (ymax+ (reduce #'max ys+ :initial-value most-negative-fixnum))
          (ymax- (reduce #'max ys- :initial-value most-negative-fixnum))
          (xmax0 (reduce #'max xs0 :initial-value most-negative-fixnum))
          (ymax0 (reduce #'max ys0 :initial-value most-negative-fixnum))
          (xmin+ (reduce #'min xs+ :initial-value most-positive-fixnum))
          (xmin- (reduce #'min xs- :initial-value most-positive-fixnum))
          (ymin+ (reduce #'min ys+ :initial-value most-positive-fixnum))
          (ymin- (reduce #'min ys- :initial-value most-positive-fixnum))
          (xmin0 (reduce #'min xs0 :initial-value most-positive-fixnum))
          (ymin0 (reduce #'min ys0 :initial-value most-positive-fixnum)))
      (let ((t1 (* 0.5d0 (- xmax- xmax+)))
            (t2 (* 0.5d0 (- xmin- xmin+)))
            (t3 (* 0.5d0 (- ymax- ymax+)))
            (t4 (* 0.5d0 (- ymin- ymin+)))
            (t5 xmax0)
            (t6 xmin0)
            (t7 ymax0)
            (t8 ymin0))
        (println
         (min (* (- (max (- xmax- t1) (+ xmax+ t1) xmax0)
                    (min (- xmin- t1) (+ xmin+ t1) xmin0))
                 (- (max (- ymax- t1) (+ ymax+ t1) ymax0)
                    (min (- ymin- t1) (+ ymin+ t1) ymin0)))
              (* (- (max (- xmax- t2) (+ xmax+ t2) xmax0)
                    (min (- xmin- t2) (+ xmin+ t2) xmin0))
                 (- (max (- ymax- t2) (+ ymax+ t2) ymax0)
                    (min (- ymin- t2) (+ ymin+ t2) ymin0)))
              (* (- (max (- xmax- t3) (+ xmax+ t3) xmax0)
                    (min (- xmin- t3) (+ xmin+ t3) xmin0))
                 (- (max (- ymax- t3) (+ ymax+ t3) ymax0)
                    (min (- ymin- t3) (+ ymin+ t3) ymin0)))
              (* (- (max (- xmax- t4) (+ xmax+ t4) xmax0)
                    (min (- xmin- t4) (+ xmin+ t4) xmin0))
                 (- (max (- ymax- t4) (+ ymax+ t4) ymax0)
                    (min (- ymin- t4) (+ ymin+ t4) ymin0)))
               (* (- (max (- xmax- t5) (+ xmax+ t5) xmax0)
                    (min (- xmin- t5) (+ xmin+ t5) xmin0))
                 (- (max (- ymax- t5) (+ ymax+ t5) ymax0)
                    (min (- ymin- t5) (+ ymin+ t5) ymin0)))
              (* (- (max (- xmax- t6) (+ xmax+ t6) xmax0)
                    (min (- xmin- t6) (+ xmin+ t6) xmin0))
                 (- (max (- ymax- t6) (+ ymax+ t6) ymax0)
                    (min (- ymin- t6) (+ ymin+ t6) ymin0)))
              (* (- (max (- xmax- t7) (+ xmax+ t7) xmax0)
                    (min (- xmin- t7) (+ xmin+ t7) xmin0))
                 (- (max (- ymax- t7) (+ ymax+ t7) ymax0)
                    (min (- ymin- t7) (+ ymin+ t7) ymin0)))
              (* (- (max (- xmax- t8) (+ xmax+ t8) xmax0)
                    (min (- xmin- t8) (+ xmin+ t8) xmin0))
                 (- (max (- ymax- t8) (+ ymax+ t8) ymax0)
                    (min (- ymin- t8) (+ ymin+ t8) ymin0)))))))))

#-swank(main)

;; For Test
#+swank
(defun io-equal (in-string out-string &optional (func #'main))
  "Passes IN-STRING to *STANDARD-INPUT*, executes FUNC, and checks 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 "2
0 3 D
3 0 L
"
    "0
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "5
-7 -10 U
7 -6 U
-8 7 D
-3 3 D
0 -6 R
"
    "97.5
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "20
6 -10 R
-4 -9 U
9 6 D
-3 -2 R
0 7 D
4 5 D
10 -10 U
-1 -8 U
10 -6 D
8 -5 U
6 4 D
0 3 D
7 9 R
9 -4 R
3 10 D
1 9 U
1 -6 U
9 -8 R
6 7 D
7 -3 D
"
    "273
")))

Score : 600 points

Problem Statement

There are N points in a two-dimensional plane. The initial coordinates of the i-th point are (x_i, y_i). Now, each point starts moving at a speed of 1 per second, in a direction parallel to the x- or y- axis. You are given a character d_i that represents the specific direction in which the i-th point moves, as follows:

If d_i = R, the i-th point moves in the positive x direction;

If d_i = L, the i-th point moves in the negative x direction;

If d_i = U, the i-th point moves in the positive y direction;

If d_i = D, the i-th point moves in the negative y direction.

You can stop all the points at some moment of your choice after they start moving (including the moment they start moving).
Then, let x_{max} and x_{min} be the maximum and minimum among the x-coordinates of the N points, respectively. Similarly, let y_{max} and y_{min} be the maximum and minimum among the y-coordinates of the N points, respectively.

Find the minimum possible value of (x_{max} - x_{min}) \times (y_{max} - y_{min}) and print it.

Constraints

1 \leq N \leq 10^5

-10^8 \leq x_i,\ y_i \leq 10^8

x_i and y_i are integers.

d_i is R, L, U, or D.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1 d_1
x_2 y_2 d_2
.
.
.
x_N y_N d_N

Output

Print the minimum possible value of (x_{max} - x_{min}) \times (y_{max} - y_{min}).

The output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-9}.

Sample Input 1

2
0 3 D
3 0 L

Sample Output 1

0

After three seconds, the two points will meet at the origin. The value in question will be 0 at that moment.

Sample Input 2

5
-7 -10 U
7 -6 U
-8 7 D
-3 3 D
0 -6 R

Sample Output 2

97.5

The answer may not be an integer.

Sample Input 3

20
6 -10 R
-4 -9 U
9 6 D
-3 -2 R
0 7 D
4 5 D
10 -10 U
-1 -8 U
10 -6 D
8 -5 U
6 4 D
0 3 D
7 9 R
9 -4 R
3 10 D
1 9 U
1 -6 U
9 -8 R
6 7 D
7 -3 D

Sample Output 3

273


(defun split (input stack-string output-list)
  (let ((chara (car input)))
    (case chara
          ((nil) (append output-list (list stack-string)))
          (#\space (split (cdr input)
                                  '()
                                  (append output-list (list stack-string))))
          (otherwise (split (cdr input)
                                    (concatenate 'string stack-string (list chara))
                                    output-list)))))

(defun input-to-list (input)
  (mapcar #'parse-integer (split (concatenate 'list input)
                                 '()
                                 '())))

(defparameter nk (input-to-list (read-line)))
(if (eq 1 (cadr nk))
    0
    (- (car nk) (cadr nk)))

Score : 100 points

Problem Statement

Takahashi is distributing N balls to K persons.

If each person has to receive at least one ball, what is the maximum possible difference in the number of balls received between the person with the most balls and the person with the fewest balls?

Constraints

1 \leq K \leq N \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the maximum possible difference in the number of balls received.

Sample Input 1

3 2

Sample Output 1

1

The only way to distribute three balls to two persons so that each of them receives at least one ball is to give one ball to one person and give two balls to the other person.

Thus, the maximum possible difference in the number of balls received is 1.

Sample Input 2

3 1

Sample Output 2

0

We have no choice but to give three balls to the only person, in which case the difference in the number of balls received is 0.

Sample Input 3

8 5

Sample Output 3

3

For example, if we give 1, 4, 1, 1, 1 balls to the five persons, the number of balls received between the person with the most balls and the person with the fewest balls would be 3, which is the maximum result.


(let* ((a (sort (list (read) (read) (read)) #'<) ))
  (princ (+ (first a) (second a))))

Score : 100 points

Problem Statement

There are three airports A, B and C, and flights between each pair of airports in both directions.

A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours.

Consider a route where we start at one of the airports, fly to another airport and then fly to the other airport.

What is the minimum possible sum of the flight times?

Constraints

1 \leq P,Q,R \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

P Q R

Output

Print the minimum possible sum of the flight times.

Sample Input 1

1 3 4

Sample Output 1

4

The sum of the flight times in the route A \rightarrow B \rightarrow C: 1 + 3 = 4 hours

The sum of the flight times in the route A \rightarrow C \rightarrow C: 4 + 3 = 7 hours

The sum of the flight times in the route B \rightarrow A \rightarrow C: 1 + 4 = 5 hours

The sum of the flight times in the route B \rightarrow C \rightarrow A: 3 + 4 = 7 hours

The sum of the flight times in the route C \rightarrow A \rightarrow B: 4 + 1 = 5 hours

The sum of the flight times in the route C \rightarrow B \rightarrow A: 3 + 1 = 4 hours

The minimum of these is 4 hours.

Sample Input 2

3 2 3

Sample Output 2

5


(defun sum(lis)
  (eval (cons '+ lis)))

(defun read-list(N &optional (l nil))
  (if (<= N 0) l (read-list  (1- N) (cons (read) l))))

(defun solve(l &optional (p (sum l)))
  (let ((n (- p (* 2 (car l)))))
    (if (< (abs p) (abs n)) (abs p)
      (solve (cdr l) n))))

(princ (solve (read-list (read))))

Score : 200 points

Problem Statement

We have N weights indexed 1 to N. The mass of the weight indexed i is W_i.

We will divide these weights into two groups: the weights with indices not greater than T, and those with indices greater than T, for some integer 1 \leq T < N. Let S_1 be the sum of the masses of the weights in the former group, and S_2 be the sum of the masses of the weights in the latter group.

Consider all possible such divisions and find the minimum possible absolute difference of S_1 and S_2.

Constraints

2 \leq N \leq 100

1 \leq W_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
W_1 W_2 ... W_{N-1} W_N

Output

Print the minimum possible absolute difference of S_1 and S_2.

Sample Input 1

3
1 2 3

Sample Output 1

0

If T = 2, S_1 = 1 + 2 = 3 and S_2 = 3, with the absolute difference of 0.

Sample Input 2

4
1 3 1 1

Sample Output 2

2

If T = 2, S_1 = 1 + 3 = 4 and S_2 = 1 + 1 = 2, with the absolute difference of 2. We cannot have a smaller absolute difference.

Sample Input 3

8
27 23 76 2 3 5 62 52

Sample Output 3

2


(defun abc129b ()
  (let* ((n (read))
	 (sa 10000)
	 (wn (loop repeat n
		collect (read))))
    (loop for i from 1 below n
       do (let* ((wa1 (apply #'+ (subseq wn 0 i)))
		 (wa2 (apply #'+ (subseq wn i)))
		 (sai (abs (- wa1 wa2))))
	    (when (> sa sai)
	      (setf sa sai))))
    (format t "~d~%" sa)))

(abc129b)


(let* ((a (read))
       (lst (loop :repeat a :collect (read)))
       (tt (reduce #'+ lst)))
  (princ (reduce #'min (maplist (lambda (k) (abs (- (reduce #'+ k) (- tt (reduce #'+ k))))) lst))))


(defun memo (fn)
    (declare (type function fn))
    (let ((table (make-hash-table :test 'equal)))
        #'(lambda (&rest rest)
              (multiple-value-bind (val found-p) (gethash rest table)
                  (if found-p
                      val
                      (setf (gethash rest table) (apply fn rest)))))))

(defun memoize (fn-name)
    (declare (type symbol fn-name))
    (setf (symbol-function fn-name) (memo (symbol-function fn-name))))

(defmacro defun-memo (fn args &body body)
    `(memoize (defun ,fn ,args . ,body)))

(defvar *mod* 1000000007)
(defparameter *unuse-lst* '())

(defun-memo find-element (elem)
    (declare (type fixnum elem))
    (not (null (find elem *unuse-lst*))))

(defun-memo rec (goal now)
    (declare (type fixnum goal now))
    (cond ((eq goal now) 1)
        ((< goal now) 0)
        ((find-element now) 0)
        (t (+ (rec goal (+ 1 now))
               (rec goal (+ 2 now))))))

(defun solve (goal)
    (declare (type fixnum goal))
    (let ((result (the fixnum (rec goal 0))))
        (print (rem result *mod*))))

(let ((goal (read))
         (num (read)))
    (dotimes (i num)
        (push (read) *unuse-lst*))
    (solve goal))

Score : 300 points

Problem Statement

There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step.
He can climb up one or two steps at a time.

However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps.

How many are there to climb up to the top step, that is, the N-th step, without setting foot on the broken steps?
Find the count modulo 1\ 000\ 000\ 007.

Constraints

1 \leq N \leq 10^5

0 \leq M \leq N-1

1 \leq a_1 < a_2 < ... < a_M \leq N-1

Input

Input is given from Standard Input in the following format:

N M
a_1
a_2
.
.
.
a_M

Output

Print the number of ways to climb up the stairs under the condition, modulo 1\ 000\ 000\ 007.

Sample Input 1

6 1
3

Sample Output 1

4

There are four ways to climb up the stairs, as follows:

0 \to 1 \to 2 \to 4 \to 5 \to 6

0 \to 1 \to 2 \to 4 \to 6

0 \to 2 \to 4 \to 5 \to 6

0 \to 2 \to 4 \to 6

Sample Input 2

10 2
4
5

Sample Output 2

0

There may be no way to climb up the stairs without setting foot on the broken steps.

Sample Input 3

100 5
1
23
45
67
89

Sample Output 3

608200469

Be sure to print the count modulo 1\ 000\ 000\ 007.


(defun memo (fn)
    (let ((table (make-hash-table :test 'equal)))
        #'(lambda (&rest rest)
              (multiple-value-bind (val found-p) (gethash rest table)
                  (if found-p
                      val
                      (setf (gethash rest table) (apply fn rest)))))))

(defun memoize (fn-name)
    (setf (symbol-function fn-name) (memo (symbol-function fn-name))))

(defmacro defun-memo (fn args &body body)
    `(memoize (defun ,fn ,args . ,body)))

(defvar *mod* 1000000007)

(defun-memo rec (goal unuse-lst now)
    (cond ((eq goal now) 1)
        ((< goal now) 0)
        ((not (null (find now unuse-lst))) 0)
        (t (+ (rec goal unuse-lst (+ 1 now))
               (rec goal unuse-lst (+ 2 now))))))

(defun solve (goal unuse-lst)
    (let ((result (rec goal unuse-lst 0)))
        (print (mod result *mod*))))

(let ((goal (read))
         (num (read))
         (lst '()))
    (dotimes (i num)
        (push (read) lst))
    (solve goal lst))


(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))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

(deftype int32 () '(signed-byte 32))
(deftype int64 () '(signed-byte 64))

;;macros
(defmacro println (n)
  `(format t "~a~%" ,n))
(defmacro vint-out (vec)
  `(progn
     (rep i (length ,vec)
          (princ (vref ,vec i))
          (princ " "))
     (fresh-line)))
(defmacro aif (test-form then-form &optional else-form)
  `(let ((it ,test-form))
     (if it ,then-form ,else-form)))

;;vector
(defmacro vec (type &optional (num 100) (val 0))
  (let* ((g (gensym)))
    `(let* ((,g ,num))
       (make-array ,g :element-type ',type :initial-element ,val
                   :adjustable nil :fill-pointer ,g))))

(defmacro double-vec (type &optional (dim1 100) (dim2 100) (val 0))
  `(make-array '(,dim1 ,dim2) :element-type ',type :initial-element ,val))

(defmacro vint (&optional (num 0) (val 0))
  `(vec int32 ,num ,val))

(defmacro double-vec (type &optional (dim1 100) (dim2 100) (val 0))
  `(make-array '(,dim1 ,dim2) :element-type ',type :initial-element ,val))

(defmacro vref (vector pos &optional value)
  (let ((g (gensym)))
    `(let ((,g ,value))
       (if ,g
           (setf (aref ,vector ,pos) ,g)
           (aref ,vector ,pos)))))

(defmacro chvar (sym comp predicate)
  (let ((g (gensym)))
    `(let ((,g ,comp))
       (if (or (null ,sym) (not (funcall ,predicate ,sym ,g)))
           (setf ,sym ,g)))))

(defmacro chmax (sym comp &optional (predicate #'>))
  `(chvar ,sym ,comp ,predicate))

(defmacro chmin (sym comp &optional (predicate #'<))
  `(chvar ,sym ,comp ,predicate))

(defmacro defchangef (name op default-val)
  `(defmacro ,name (var &optional (val ,default-val))
     `(setq ,var (,',op ,val ,var))))
(defmacro read-str ()
  `(write-to-string (read)))

;;本体
(defconstant *mod* 1000000007)
(defvar n (read))
(defvar m (read))
(defvar fib
  (make-array (1+ n)))

(vref fib 0 1)
(vref fib 1 1)
(loop for i from 2 to n
   do (vref fib i (mod
                   (+ (vref fib (1- i))
                      (vref fib (- i 2)))
                   *mod*)))
(vref fib 1 0)

(defun main ()
  (let ((ans 1) (pos 0) next)
    (dotimes (i m)
      (setf next (1- (read)))
      (if (< (- next pos) 0)
          (setf ans 0)
          (setf ans (mod (* ans (vref fib (- next pos))) *mod*)))
      (setf pos (+ 2 next)))
    (setf ans (mod (* ans (vref fib (- n pos))) *mod*))
    (println ans)))

#-swank(main)


(defun split (input stack-string output-list)
  (let ((chara (car input)))
    (case chara
          ((nil) (append output-list (list stack-string)))
          (#\space (split (cdr input)
                                  '()
                                  (append output-list (list stack-string))))
          (otherwise (split (cdr input)
                                    (concatenate 'string stack-string (list chara))
                                    output-list)))))

(defun input-to-list (input)
  (mapcar #'parse-integer (split (concatenate 'list input)
                                 '()
                                 '())))

(defparameter hw (input-to-list (read-line)))
(defparameter stage (loop for i from 1 to (car hw)
                          collect (read-line)))

(defun sacc (stage x y)
  (schar (nth y stage) x))

#| (defun idn (&rest lst)
  lst) |#

#| (defun lit (x y stage hw)
  (if (eq #\. (sacc stage x y))
      (labels ((count-lit (x y direction cnt)
                          (format t "coor: ~d, ~d~%dir: ~d~%~%" x y direction)
                          (case direction
                            (0 (if (zerop y)
                                   cnt
                                   (if (eq #\. (sacc stage x (1- y)))
                                       (count-lit x (1- y) 0 (1+ cnt))
                                       cnt)))
                            (1 (if (eq y (1- (car hw)))
                                   cnt
                                   (if (eq #\. (sacc stage x (1+ y)))
                                       (count-lit x (1+ y) 0 (1+ cnt))
                                       cnt)))
                            (2 (if (zerop x)
                                   cnt
                                   (if (eq #\. (sacc stage (1- x) y))
                                       (count-lit (1- x) y 0 (1+ cnt))
                                       cnt)))
                            (3 (if (eq x (1- (cadr hw)))
                                   cnt
                                   (if (eq #\. (sacc stage (1+ x) y))
                                       (count-lit (1+ x) y 0 (1+ cnt))
                                       cnt))))))
          (1+ (apply #'+ (loop for i from 0 to 3
                           collect (count-lit x y i 0)))))
      0)) |#

(defun l-lit (x y cnt)
  (if (zerop x)
      cnt
      (if (eq #\. (sacc stage (1- x) y))
          (l-lit (1- x) y (1+ cnt))
          cnt)))

(defun r-lit (x y cnt)
  (if (eq x (1- (cadr hw)))
      cnt
      (if (eq #\. (sacc stage (1+ x) y))
          (r-lit (1+ x) y (1+ cnt))
          cnt)))

(defun u-lit (x y cnt)
  (if (zerop y)
      cnt
      (if (eq #\. (sacc stage x (1- y)))
          (u-lit x (1- y) (1+ cnt))
          cnt)))

(defun d-lit (x y cnt)
  (if (eq y (1- (car hw)))
      cnt
      (if (eq #\. (sacc stage x (1+ y)))
          (d-lit x (1+ y) (1+ cnt))
          cnt)))

(defun lit (x y)
  (if (eq #\. (sacc stage x y))
      (+ 1
         (l-lit x y 0)
         (r-lit x y 0)
         (u-lit x y 0)
         (d-lit x y 0))
      0))

(format t "~d" (apply #'max (loop for i from 0 to (1- (cadr hw))
                          collect (apply #'max (loop for j from 0 to (1- (car hw))
                                             collect (lit i j))))))

Score : 400 points

Problem Statement

There is a grid with H horizontal rows and W vertical columns, and there are obstacles on some of the squares.

Snuke is going to choose one of the squares not occupied by an obstacle and place a lamp on it.
The lamp placed on the square will emit straight beams of light in four cardinal directions: up, down, left, and right.
In each direction, the beam will continue traveling until it hits a square occupied by an obstacle or it hits the border of the grid. It will light all the squares on the way, including the square on which the lamp is placed, but not the square occupied by an obstacle.

Snuke wants to maximize the number of squares lighted by the lamp.

You are given H strings S_i (1 \leq i \leq H), each of length W. If the j-th character (1 \leq j \leq W) of S_i is #, there is an obstacle on the square at the i-th row from the top and the j-th column from the left; if that character is ., there is no obstacle on that square.

Find the maximum possible number of squares lighted by the lamp.

Constraints

1 \leq H \leq 2,000

1 \leq W \leq 2,000

S_i is a string of length W consisting of # and ..

. occurs at least once in one of the strings S_i (1 \leq i \leq H).

Input

Input is given from Standard Input in the following format:

H W
S_1
:
S_H

Output

Print the maximum possible number of squares lighted by the lamp.

Sample Input 1

4 6
#..#..
.....#
....#.
#.#...

Sample Output 1

8

If Snuke places the lamp on the square at the second row from the top and the second column from the left, it will light the following squares: the first through fifth squares from the left in the second row, and the first through fourth squares from the top in the second column, for a total of eight squares.

Sample Input 2

8 8
..#...#.
....#...
##......
..###..#
...#..#.
##....#.
#...#...
###.#..#

Sample Output 2

13


;; -*- 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))
                 (shadow :run)
                 (use-package :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)

;; BEGIN_INSERTED_CONTENTS
(declaim (inline power-mod))
(defun power-mod (base power &optional (divisor 1000000007))
  "BASE := integer
POWER, DIVISOR := non-negative fixnum"
  (declare ((integer 0 #.most-positive-fixnum) divisor)
           (integer base))
  (labels ((recur (x p)
             (declare ((integer 0 #.most-positive-fixnum) x)
                      (unsigned-byte p))
             (cond ((zerop p) 1)
                   ((evenp p) (recur (mod (* x x) divisor) (ash p -1)))
                   (t (mod (* x (recur x (- p 1))) divisor)))))
    (declare (ftype (function * (values (integer 0 #.most-positive-fixnum) &optional))
                    recur))
    (recur (mod base divisor) power)))

(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 sum10 (k width divisor)
  (let ((factor (mod (expt 10 width) divisor)))
    (labels ((recur (k)
               (cond ((zerop k) 0)
                     ((evenp k)
                      (mod (* (recur (ash k -1))
                              (+ 1 (power-mod factor (ash k -1) divisor)))
                           divisor))
                     (t
                      (mod (+ 1 (* factor (recur (- k 1))))
                           divisor)))))
      (recur k))))

(defun calc (k init delta width divisor)
  (let ((factor (mod (expt 10 width) divisor)))
    (labels ((mod+ (x y) (mod (+ x y) divisor))
             (mod* (x y) (mod (* x y) divisor))
             (recur (k)
               (cond ((zerop k) 0)
                     ((evenp k)
                      (mod+ (mod* (mod* (ash k -1) delta)
                                  (sum10 (ash k -1) width divisor))
                            (mod* (+ 1 (power-mod factor (ash k -1) divisor))
                                  (recur (ash k -1)))))
                     (t (mod+ (mod* factor (recur (- k 1)))
                              (mod+ init (mod* (- k 1) delta)))))))
      (declare (inline mod+ mod*))
      (recur k))))

(defun main ()
  (let* ((l (read))
         (a (read))
         (b (read))
         (m (read))
         (boundaries (make-array 19 :element-type 'fixnum :initial-element 0)))
    (dotimes (d 19)
      (setf (aref boundaries d)
            (max 0 (ceiling (- (expt 10 d) a) b))))
    (let ((res 0))
      (loop for d from (position-if #'plusp boundaries) below 19
            for length = (* d (- (aref boundaries d) (aref boundaries (- d 1))))
            until (>= (aref boundaries d) l)
            do (setf res
                     (mod
                      (+ (mod (* res (power-mod 10 length m)) m)
                         (calc (- (aref boundaries d) (aref boundaries (- d 1)))
                               (+ a (* b (aref boundaries (- d 1)))) b d m))
                      m))
            finally (setf res
                     (mod
                      (+ (mod (* res (power-mod 10 (* d (- l (aref boundaries (- d 1)))) m)) m)
                         (calc (- l (aref boundaries (- d 1)))
                               (+ a (* b (aref boundaries (- d 1)))) b d m))
                      m)))
      (println res))))

#-swank(main)

Score : 600 points

Problem Statement

There is an arithmetic progression with L terms: s_0, s_1, s_2, ... , s_{L-1}.

The initial term is A, and the common difference is B. That is, s_i = A + B \times i holds.

Consider the integer obtained by concatenating the terms written in base ten without leading zeros. For example, the sequence 3, 7, 11, 15, 19 would be concatenated into 37111519. What is the remainder when that integer is divided by M?

Constraints

All values in input are integers.

1 \leq L, A, B < 10^{18}

2 \leq M \leq 10^9

All terms in the arithmetic progression are less than 10^{18}.

Input

Input is given from Standard Input in the following format:

L A B M

Output

Print the remainder when the integer obtained by concatenating the terms is divided by M.

Sample Input 1

5 3 4 10007

Sample Output 1

5563

Our arithmetic progression is 3, 7, 11, 15, 19, so the answer is 37111519 mod 10007, that is, 5563.

Sample Input 2

4 8 1 1000000

Sample Output 2

891011

Sample Input 3

107 10000000000007 1000000000000007 998244353

Sample Output 3

39122908


Score : 100 points

Problem Statement

Given an integer N not less than 3, find the sum of the interior angles of a regular polygon with N sides.

Print the answer in degrees, but do not print units.

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print an integer representing the sum of the interior angles of a regular polygon with N sides.

Sample Input 1

3

Sample Output 1

180

The sum of the interior angles of a regular triangle is 180 degrees.

Sample Input 2

100

Sample Output 2

17640


Score : 100 points

Problem Statement

We have A apples and P pieces of apple.

We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan.

Find the maximum number of apple pies we can make with what we have now.

Constraints

All values in input are integers.

0 \leq A, P \leq 100

Input

Input is given from Standard Input in the following format:

A P

Output

Print the maximum number of apple pies we can make with what we have.

Sample Input 1

1 3

Sample Output 1

3

We can first make one apple pie by simmering two of the three pieces of apple. Then, we can make two more by simmering the remaining piece and three more pieces obtained by cutting the whole apple.

Sample Input 2

0 1

Sample Output 2

0

We cannot make an apple pie in this case, unfortunately.

Sample Input 3

32 21

Sample Output 3

58