#-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
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

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

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

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

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

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

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

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

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

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

;;;
;;; Binary heap
;;;

(define-condition heap-empty-error (error)
  ((heap :initarg :heap :reader heap-empty-error-heap))
  (:report
   (lambda (condition stream)
     (format stream "Attempted to pop empty heap ~W" (heap-empty-error-heap condition)))))

(defmacro define-binary-heap (name &key (order '#'>) (element-type 'fixnum))
  "Defines a binary heap specialized for the given order and the element
type. This macro defines a structure of the given NAME and relevant functions:
MAKE-<NAME>, <NAME>-PUSH, <NAME>-POP, <NAME>-REINITIALIZE, <NAME>-EMPTY-P,
<NAME>-COUNT, and <NAME>-PEEK."
  (check-type name symbol)
  (let* ((string-name (string name))
         (fname-push (intern (format nil "~A-PUSH" string-name)))
         (fname-pop (intern (format nil "~A-POP" string-name)))
         (fname-reinitialize (intern (format nil "~A-REINITIALIZE" string-name)))
         (fname-empty-p (intern (format nil "~A-EMPTY-P" string-name)))
         (fname-count (intern (format nil "~A-COUNT" string-name)))
         (fname-peek (intern (format nil "~A-PEEK" string-name)))
         (fname-make (intern (format nil "MAKE-~A" string-name)))
         (acc-position (intern (format nil "~A-POSITION" string-name)))
         (acc-data (intern (format nil "~A-DATA" string-name))))
    `(progn
       (locally
           ;; prevent style warnings
           (declare #+sbcl (muffle-conditions style-warning))
         (defstruct (,name
                     (:constructor ,fname-make
                         (size
                          &aux
                          (data (make-array (1+ size)
                                            :element-type ',(if (eql element-type '*) t  element-type))))))
           (data nil :type (simple-array ,element-type (*)))
           (position 1 :type (integer 1 #.array-total-size-limit))))

       (declaim #+sbcl (sb-ext:maybe-inline ,fname-push))
       (defun ,fname-push (obj heap)
         "Adds OBJ to HEAP."
         (declare (optimize (speed 3))
                  (type ,name heap))
         (symbol-macrolet ((position (,acc-position heap)))
           (when (>= position (length (,acc-data heap)))
             (setf (,acc-data heap)
                   (adjust-array (,acc-data heap)
                                 (min (- array-total-size-limit 1)
                                      (* position 2)))))
           (let ((data (,acc-data heap)))
             (declare ((simple-array ,element-type (*)) data))
             (labels ((heapify (pos)
                        (declare (optimize (speed 3) (safety 0)))
                        (unless (= pos 1)
                          (let ((parent-pos (ash pos -1)))
                            (when (funcall ,order (aref data pos) (aref data parent-pos))
                              (rotatef (aref data pos) (aref data parent-pos))
                              (heapify parent-pos))))))
               (setf (aref data position) obj)
               (heapify position)
               (incf position)
               heap))))

       (declaim #+sbcl (sb-ext:maybe-inline ,fname-pop))
       (defun ,fname-pop (heap)
         "Removes and returns the element at the top of HEAP."
         (declare (optimize (speed 3))
                  (type ,name heap))
         (symbol-macrolet ((position (,acc-position heap)))
           (let ((data (,acc-data heap)))
             (declare ((simple-array ,element-type (*)) data))
             (labels ((heapify (pos)
                        (declare (optimize (speed 3) (safety 0))
                                 ((integer 1 #.array-total-size-limit) pos))
                        (let* ((child-pos1 (+ pos pos))
                               (child-pos2 (1+ child-pos1)))
                          (when (<= child-pos1 position)
                            (if (<= child-pos2 position)
                                (if (funcall ,order (aref data child-pos1) (aref data child-pos2))
                                    (unless (funcall ,order (aref data pos) (aref data child-pos1))
                                      (rotatef (aref data pos) (aref data child-pos1))
                                      (heapify child-pos1))
                                    (unless (funcall ,order (aref data pos) (aref data child-pos2))
                                      (rotatef (aref data pos) (aref data child-pos2))
                                      (heapify child-pos2)))
                                (unless (funcall ,order (aref data pos) (aref data child-pos1))
                                  (rotatef (aref data pos) (aref data child-pos1))))))))
               (when (= position 1)
                 (error 'heap-empty-error :heap heap))
               (prog1 (aref data 1)
                 (decf position)
                 (setf (aref data 1) (aref data position))
                 (heapify 1))))))

       (declaim (inline ,fname-reinitialize))
       (defun ,fname-reinitialize (heap)
         "Makes HEAP empty."
         (setf (,acc-position heap) 1)
         heap)

       (declaim (inline ,fname-empty-p))
       (defun ,fname-empty-p (heap)
         "Returns true iff HEAP is empty."
         (= 1 (,acc-position heap)))

       (declaim (inline ,fname-count))
       (defun ,fname-count (heap)
         "Returns the current number of the elements in HEAP."
         (- (,acc-position heap) 1))

       (declaim (inline ,fname-peek))
       (defun ,fname-peek (heap)
         "Returns the topmost element of HEAP."
         (if (= 1 (,acc-position heap))
             (error 'heap-empty-error :heap heap)
             (aref (,acc-data heap) 1))))))

(in-package :cl-user)

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

;; dist . v
(define-binary-heap heap
  :order (lambda (x y)
           (< (the fixnum (car x)) (the fixnum (car y))))
  :element-type list)

(define-mod-operations +mod+)

(defconstant +inf+ most-positive-fixnum)
(defun make-dists (n m src graph)
  (declare #.opt
           ((simple-array list (*)) graph))
  (let* ((dists (make-array n :element-type 'uint62 :initial-element +inf+))
         (que (make-heap m)))
    (setf (aref dists src) 0)
    (heap-push (cons 0 src) que)
    (loop until (heap-empty-p que)
          for (dist . v) of-type (uint62 . uint62) = (heap-pop que)
          when (= dist (aref dists v))
          do (loop for (next . d) of-type (uint62 . uint62) in (aref graph v)
                   for next-dist = (+ d dist)
                   when (< next-dist (aref dists next))
                   do (setf (aref dists next) next-dist)
                      (heap-push (cons next-dist next) que)))
    (let ((dp (make-array n :element-type 'uint31 :initial-element 0))
          (visited (make-array n :element-type 'bit :initial-element 0))
          (ords (make-array n :element-type 'uint31 :initial-element 0))
          (index (- n 1)))
      (declare (int32 index))
      (setf (aref dp src) 1)
      (sb-int:named-let dfs ((v src))
        (when (zerop (aref visited v))
          (setf (aref visited v) 1)
          (loop for (next . d) of-type (uint62 . uint62) in (aref graph v)
                when (= (+ (aref dists v) d) (aref dists next))
                do (dfs next))
          (setf (aref ords index) v
                index (- index 1))))
      (sb-int:dovector (v ords)
        (loop for (next . d) of-type (uint62 . uint62) in (aref graph v)
              when (= (+ (aref dists v) d) (aref dists next))
              do (incfmod (aref dp next) (aref dp v))))
      (values dists dp))))

(defun main ()
  (declare #.opt)
  (let* ((n (read))
         (m (read))
         (ss (- (read) 1))
         (tt (- (read) 1))
         (graph (make-array n :element-type 'list :initial-element nil)))
    (declare (uint31 n m ss tt))
    (dotimes (i m)
      (let ((u (- (read-fixnum) 1))
            (v (- (read-fixnum) 1))
            (d (read-fixnum)))
        (push (cons u d) (aref graph v))
        (push (cons v d) (aref graph u))))
    (multiple-value-bind (dists+ dp+) (make-dists n m ss graph)
      (multiple-value-bind (dists- dp-) (make-dists n m tt graph)
        (declare ((simple-array uint62 (*)) dists+ dists-)
                 ((simple-array uint31 (*)) dp+ dp-))
        (let ((l (aref dists+ tt))
              (res (mod* (aref dp+ tt) (aref dp- ss))))
          (declare (uint31 res))
          (dotimes (v n)
            (when (= (+ (aref dists+ v) (aref dists- v)) l)
              (when (= (* 2 (aref dists+ v)) l)
                (decfmod res (mod* (aref dp+ v) (aref dp- v)
                                   (aref dp+ v) (aref dp- v))))
              (when (< (* 2 (aref dists+ v)) l)
                (loop for (next . d) in (aref graph v)
                      when (and (< (* 2 (aref dists- next)) l)
                                (= l (+ (aref dists+ v) (aref dists- next) d)))
                      do (decfmod res (mod* (aref dp+ v) (aref dp- next)
                                            (aref dp+ v) (aref dp- next)))))))
          (println res))))))

#-swank (main)

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

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

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

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

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

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

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

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

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

Score : 700 points

Problem Statement

We have a graph with N vertices and M edges, and there are two people on the graph: Takahashi and Aoki.

The i-th edge connects Vertex U_i and Vertex V_i.
The time it takes to traverse this edge is D_i minutes, regardless of direction and who traverses the edge (Takahashi or Aoki).

Takahashi departs Vertex S and Aoki departs Vertex T at the same time. Takahashi travels to Vertex T and Aoki travels to Vertex S, both in the shortest time possible.
Find the number of the pairs of ways for Takahashi and Aoki to choose their shortest paths such that they never meet (at a vertex or on an edge) during the travel, modulo 10^9 + 7.

Constraints

1 \leq N \leq 100 000

1 \leq M \leq 200 000

1 \leq S, T \leq N

S \neq T

1 \leq U_i, V_i \leq N (1 \leq i \leq M)

1 \leq D_i \leq 10^9 (1 \leq i \leq M)

If i \neq j, then (U_i, V_i) \neq (U_j, V_j) and (U_i, V_i) \neq (V_j, U_j).

U_i \neq V_i (1 \leq i \leq M)

D_i are integers.

The given graph is connected.

Input

Input is given from Standard Input in the following format:

N M
S T
U_1 V_1 D_1
U_2 V_2 D_2
:
U_M V_M D_M

Output

Print the answer.

Sample Input 1

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

Sample Output 1

2

There are two ways to choose shortest paths that satisfies the condition:

Takahashi chooses the path 1 \rightarrow 2 \rightarrow 3, and Aoki chooses the path 3 \rightarrow 4 \rightarrow 1.

Takahashi chooses the path 1 \rightarrow 4 \rightarrow 3, and Aoki chooses the path 3 \rightarrow 2 \rightarrow 1.

Sample Input 2

3 3
1 3
1 2 1
2 3 1
3 1 2

Sample Output 2

2

Sample Input 3

3 3
1 3
1 2 1
2 3 1
3 1 2

Sample Output 3

2

Sample Input 4

8 13
4 2
7 3 9
6 2 3
1 6 4
7 6 9
3 8 9
1 2 2
2 8 12
8 6 9
2 5 5
4 2 18
5 3 7
5 1 515371567
4 8 6

Sample Output 4

6


#-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
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

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

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

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

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

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

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

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

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

;;;
;;; Memoization macro
;;;

;;
;; Basic usage:
;;
;; (with-cache (:hash-table :test #'equal :key #'cons)
;;   (defun add (a b)
;;     (+ a b)))
;; This function caches the returned values for already passed combinations of
;; arguments. In this case ADD stores the key (CONS A B) and the returned value
;; to a hash-table when (ADD A B) is evaluated for the first time. ADD returns
;; the stored value when it is called with the same arguments (w.r.t. EQUAL)
;; again.
;;
;; The storage for cache can be hash-table or array. Let's see an example for
;; array:
;; (with-cache (:array (10 20 30) :initial-element -1 :element-type 'fixnum)
;;   (defun foo (a b c) ... ))
;; This form stores the value of FOO in an array created by (make-array (list 10
;; 20 30) :initial-element -1 :element-type 'fixnum). Note that INITIAL-ELEMENT
;; must always be given here as it is used as the flag expressing `not yet
;; stored'. (Therefore INITIAL-ELEMENT should be a value FOO never takes.)
;;
;; If you want to ignore some arguments, you can put `*' in dimensions:
;; (with-cache (:array (10 10 * 10) :initial-element -1)
;;   (defun foo (a b c d) ...)) ; then C is ignored when querying or storing cache
;;
;; Available definition forms in WITH-CACHE are DEFUN, LABELS, FLET, and
;; SB-INT:NAMED-LET.
;;
;; You can trace the memoized function by :TRACE option:
;; (with-cache (:array (10 10) :initial-element -1 :trace t)
;;   (defun foo (x y) ...))
;; Then FOO is traced as with CL:TRACE.
;;

;; TODO & NOTE: Currently a memoized function is not enclosed with a block of
;; the function name.

;; FIXME: *RECURSION-DEPTH* should be included within the macro.
(declaim (type (integer 0 #.most-positive-fixnum) *recursion-depth*))
(defparameter *recursion-depth* 0)

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defun %enclose-with-trace (fname args form)
    (let ((value (gensym)))
      `(progn
         (format t "~&~A~A: (~A ~{~A~^ ~}) =>"
                 (make-string *recursion-depth*
                              :element-type 'base-char
                              :initial-element #\ )
                 *recursion-depth*
                 ',fname
                 (list ,@args))
         (let ((,value (let ((*recursion-depth* (1+ *recursion-depth*)))
                         ,form)))
           (format t "~&~A~A: (~A ~{~A~^ ~}) => ~A"
                   (make-string *recursion-depth*
                                :element-type 'base-char
                                :initial-element #\ )
                   *recursion-depth*
                   ',fname
                   (list ,@args)
                   ,value)
           ,value))))

  (defun %extract-declarations (body)
    (remove-if-not (lambda (form) (and (consp form) (eql 'declare (car form))))
                   body))

  (defun %parse-cache-form (cache-specifier)
    (let ((cache-type (car cache-specifier))
          (cache-attribs (cdr cache-specifier)))
      (assert (member cache-type '(:hash-table :array)))
      (let* ((dims-with-* (when (eql cache-type :array) (first cache-attribs)))
             (dims (remove '* dims-with-*))
             (rank (length dims))
             (rest-attribs (ecase cache-type
                             (:hash-table cache-attribs)
                             (:array (cdr cache-attribs))))
             (key (prog1 (getf rest-attribs :key) (remf rest-attribs :key)))
             (trace-p (prog1 (getf rest-attribs :trace) (remf rest-attribs :trace)))
             (cache-form (case cache-type
                           (:hash-table `(make-hash-table ,@rest-attribs))
                           (:array `(make-array (list ,@dims) ,@rest-attribs))))
             (initial-element (when (eql cache-type :array)
                                (assert (member :initial-element rest-attribs))
                                (getf rest-attribs :initial-element))))
        (let ((cache (gensym "CACHE"))
              (value (gensym))
	      (present-p (gensym))
              (name-alias (gensym))
	      (args-lst (gensym))
              (indices (loop repeat rank collect (gensym))))
          (labels
              ((make-cache-querier (cache-type name args)
                 (let ((res (case cache-type
                              (:hash-table
                               `(let ((,args-lst (funcall ,(or key '#'list) ,@args)))
                                  (multiple-value-bind (,value ,present-p)
                                      (gethash ,args-lst ,cache)
                                    (if ,present-p
                                        ,value
                                        (setf (gethash ,args-lst ,cache)
                                              (,name-alias ,@args))))))
                              (:array
                               (assert (= (length args) (length dims-with-*)))
                               (let ((memoized-args (loop for dimension in dims-with-*
                                                          for arg in args
                                                          unless (eql dimension '*)
                                                          collect arg)))
                                 (if key
                                     `(multiple-value-bind ,indices
                                          (funcall ,key ,@memoized-args)
                                        (let ((,value (aref ,cache ,@indices)))
                                          (if (eql ,initial-element ,value)
                                              (setf (aref ,cache ,@indices)
                                                    (,name-alias ,@args))
                                              ,value)))
                                     `(let ((,value (aref ,cache ,@memoized-args)))
                                        (if (eql ,initial-element ,value)
                                            (setf (aref ,cache ,@memoized-args)
                                                  (,name-alias ,@args))
                                            ,value))))))))
                   (if trace-p
                       (%enclose-with-trace name args res)
                       res)))
               (make-reset-form (cache-type)
                 (case cache-type
                   (:hash-table `(setf ,cache (make-hash-table ,@rest-attribs)))
                   (:array `(prog1 nil
                              ;; TODO: portable fill
                              (fill (array-storage-vector ,cache) ,initial-element)))))
               (make-reset-name (name)
                 (intern (format nil "RESET-~A" (symbol-name name)))))
            (values cache cache-form cache-type name-alias
                    #'make-reset-name
                    #'make-reset-form
                    #'make-cache-querier)))))))

(defmacro with-cache ((cache-type &rest cache-attribs) def-form)
  "CACHE-TYPE := :HASH-TABLE | :ARRAY.
DEF-FORM := definition form with DEFUN, LABELS, FLET, or SB-INT:NAMED-LET."
  (multiple-value-bind (cache-symbol cache-form cache-type name-alias
                        make-reset-name make-reset-form
                        make-cache-querier)
      (%parse-cache-form (cons cache-type cache-attribs))
    (ecase (car def-form)
      ((defun)
       (destructuring-bind (_ name args &body body) def-form
         (declare (ignore _))
         `(let ((,cache-symbol ,cache-form))
            (defun ,(funcall make-reset-name name) ()
              ,(funcall make-reset-form cache-type))
            (defun ,name ,args
              ,@(%extract-declarations body)
              (labels ((,name-alias ,args ,@body))
                (declare (inline ,name-alias))
                ,(funcall make-cache-querier cache-type name args))))))
      ((labels flet)
       (destructuring-bind (_ definitions &body labels-body) def-form
         (declare (ignore _))
         (destructuring-bind (name args &body body) (car definitions)
           `(let ((,cache-symbol ,cache-form))
              (,(car def-form)
               ((,(funcall make-reset-name name) ()
                 ,(funcall make-reset-form cache-type))
                (,name ,args
                       ,@(%extract-declarations body)
                       (labels ((,name-alias ,args ,@body))
                         (declare (inline ,name-alias))
                         ,(funcall make-cache-querier cache-type name args)))
                ,@(cdr definitions))
               (declare (ignorable #',(funcall make-reset-name name)))
               ,@labels-body)))))
      ((nlet #+sbcl sb-int:named-let)
       (destructuring-bind (_ name bindings &body body) def-form
         (declare (ignore _))
         `(let ((,cache-symbol ,cache-form))
            (,(car def-form) ,name ,bindings
             ,@(%extract-declarations body)
             ,(let ((args (mapcar (lambda (x) (if (atom x) x (car x))) bindings)))
                `(labels ((,name-alias ,args ,@body))
                   (declare (inline ,name-alias))
                   ,(funcall make-cache-querier cache-type name args))))))))))

(defmacro with-caches (cache-specs def-form)
  "DEF-FORM := definition form by LABELS or FLET.

 (with-caches (cache-spec1 cache-spec2)
   (labels ((f (x) ...) (g (y) ...))))
is equivalent to the line up of
 (with-cache cache-spec1 (labels ((f (x) ...))))
and
 (with-cache cache-spec2 (labels ((g (y) ...))))

This macro will be useful to do mutual recursion between memoized local
functions."
  (assert (member (car def-form) '(labels flet)))
  (let (cache-symbol-list cache-form-list cache-type-list name-alias-list make-reset-name-list make-reset-form-list make-cache-querier-list)
    (dolist (cache-spec (reverse cache-specs))
      (multiple-value-bind (cache-symbol cache-form cache-type name-alias
                            make-reset-name make-reset-form make-cache-querier)
          (%parse-cache-form cache-spec)
        (push cache-symbol cache-symbol-list)
        (push cache-form cache-form-list)
        (push cache-type cache-type-list)
        (push name-alias name-alias-list)
        (push make-reset-name make-reset-name-list)
        (push make-reset-form make-reset-form-list)
        (push make-cache-querier make-cache-querier-list)))
    (labels ((def-name (def) (first def))
             (def-args (def) (second def))
             (def-body (def) (cddr def)))
      (destructuring-bind (_ definitions &body labels-body) def-form
        (declare (ignore _))
        `(let ,(loop for cache-symbol in cache-symbol-list
                     for cache-form in cache-form-list
                     collect `(,cache-symbol ,cache-form))
           (,(car def-form)
            (,@(loop for def in definitions
                     for cache-type in cache-type-list
                     for make-reset-name in make-reset-name-list
                     for make-reset-form in make-reset-form-list
                     collect `(,(funcall make-reset-name (def-name def)) ()
                               ,(funcall make-reset-form cache-type)))
             ,@(loop for def in definitions
                     for cache-type in cache-type-list
                     for name-alias in name-alias-list
                     for make-cache-querier in make-cache-querier-list
                     collect `(,(def-name def) ,(def-args def)
                               ,@(%extract-declarations (def-body def))
                               (labels ((,name-alias ,(def-args def) ,@(def-body def)))
                                 (declare (inline ,name-alias))
                                 ,(funcall make-cache-querier cache-type (def-name def) (def-args def))))))
            (declare (ignorable ,@(loop for def in definitions
                                        for make-reset-name in make-reset-name-list
                                        collect `#',(funcall make-reset-name
                                                             (def-name def)))))
            ,@labels-body))))))

;;;
;;; Binary heap
;;;

(define-condition heap-empty-error (error)
  ((heap :initarg :heap :reader heap-empty-error-heap))
  (:report
   (lambda (condition stream)
     (format stream "Attempted to pop empty heap ~W" (heap-empty-error-heap condition)))))

(defmacro define-binary-heap (name &key (order '#'>) (element-type 'fixnum))
  "Defines a binary heap specialized for the given order and the element
type. This macro defines a structure of the given NAME and relevant functions:
MAKE-<NAME>, <NAME>-PUSH, <NAME>-POP, <NAME>-REINITIALIZE, <NAME>-EMPTY-P,
<NAME>-COUNT, and <NAME>-PEEK."
  (check-type name symbol)
  (let* ((string-name (string name))
         (fname-push (intern (format nil "~A-PUSH" string-name)))
         (fname-pop (intern (format nil "~A-POP" string-name)))
         (fname-reinitialize (intern (format nil "~A-REINITIALIZE" string-name)))
         (fname-empty-p (intern (format nil "~A-EMPTY-P" string-name)))
         (fname-count (intern (format nil "~A-COUNT" string-name)))
         (fname-peek (intern (format nil "~A-PEEK" string-name)))
         (fname-make (intern (format nil "MAKE-~A" string-name)))
         (acc-position (intern (format nil "~A-POSITION" string-name)))
         (acc-data (intern (format nil "~A-DATA" string-name))))
    `(progn
       (locally
           ;; prevent style warnings
           (declare #+sbcl (muffle-conditions style-warning))
         (defstruct (,name
                     (:constructor ,fname-make
                         (size
                          &aux
                          (data (make-array (1+ size)
                                            :element-type ',(if (eql element-type '*) t  element-type))))))
           (data nil :type (simple-array ,element-type (*)))
           (position 1 :type (integer 1 #.array-total-size-limit))))

       (declaim #+sbcl (sb-ext:maybe-inline ,fname-push))
       (defun ,fname-push (obj heap)
         "Adds OBJ to HEAP."
         (declare (optimize (speed 3))
                  (type ,name heap))
         (symbol-macrolet ((position (,acc-position heap)))
           (when (>= position (length (,acc-data heap)))
             (setf (,acc-data heap)
                   (adjust-array (,acc-data heap)
                                 (min (- array-total-size-limit 1)
                                      (* position 2)))))
           (let ((data (,acc-data heap)))
             (declare ((simple-array ,element-type (*)) data))
             (labels ((heapify (pos)
                        (declare (optimize (speed 3) (safety 0)))
                        (unless (= pos 1)
                          (let ((parent-pos (ash pos -1)))
                            (when (funcall ,order (aref data pos) (aref data parent-pos))
                              (rotatef (aref data pos) (aref data parent-pos))
                              (heapify parent-pos))))))
               (setf (aref data position) obj)
               (heapify position)
               (incf position)
               heap))))

       (declaim #+sbcl (sb-ext:maybe-inline ,fname-pop))
       (defun ,fname-pop (heap)
         "Removes and returns the element at the top of HEAP."
         (declare (optimize (speed 3))
                  (type ,name heap))
         (symbol-macrolet ((position (,acc-position heap)))
           (let ((data (,acc-data heap)))
             (declare ((simple-array ,element-type (*)) data))
             (labels ((heapify (pos)
                        (declare (optimize (speed 3) (safety 0))
                                 ((integer 1 #.array-total-size-limit) pos))
                        (let* ((child-pos1 (+ pos pos))
                               (child-pos2 (1+ child-pos1)))
                          (when (<= child-pos1 position)
                            (if (<= child-pos2 position)
                                (if (funcall ,order (aref data child-pos1) (aref data child-pos2))
                                    (unless (funcall ,order (aref data pos) (aref data child-pos1))
                                      (rotatef (aref data pos) (aref data child-pos1))
                                      (heapify child-pos1))
                                    (unless (funcall ,order (aref data pos) (aref data child-pos2))
                                      (rotatef (aref data pos) (aref data child-pos2))
                                      (heapify child-pos2)))
                                (unless (funcall ,order (aref data pos) (aref data child-pos1))
                                  (rotatef (aref data pos) (aref data child-pos1))))))))
               (when (= position 1)
                 (error 'heap-empty-error :heap heap))
               (prog1 (aref data 1)
                 (decf position)
                 (setf (aref data 1) (aref data position))
                 (heapify 1))))))

       (declaim (inline ,fname-reinitialize))
       (defun ,fname-reinitialize (heap)
         "Makes HEAP empty."
         (setf (,acc-position heap) 1)
         heap)

       (declaim (inline ,fname-empty-p))
       (defun ,fname-empty-p (heap)
         "Returns true iff HEAP is empty."
         (= 1 (,acc-position heap)))

       (declaim (inline ,fname-count))
       (defun ,fname-count (heap)
         "Returns the current number of the elements in HEAP."
         (- (,acc-position heap) 1))

       (declaim (inline ,fname-peek))
       (defun ,fname-peek (heap)
         "Returns the topmost element of HEAP."
         (if (= 1 (,acc-position heap))
             (error 'heap-empty-error :heap heap)
             (aref (,acc-data heap) 1))))))

(in-package :cl-user)

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

;; dist . v
(define-binary-heap heap
  :order (lambda (x y)
           (< (the fixnum (car x)) (the fixnum (car y))))
  :element-type list)

(defconstant +inf+ most-positive-fixnum)
(defun make-dists (n m src graph)
  (declare ((simple-array list (*)) graph))
  (let* ((dists (make-array n :element-type 'uint62 :initial-element +inf+))
         (que (make-heap m)))
    (setf (aref dists src) 0)
    (heap-push (cons 0 src) que)
    (loop until (heap-empty-p que)
          for (dist . v) = (heap-pop que)
          when (= dist (aref dists v))
          do (loop for (next . d) in (aref graph v)
                   for next-dist = (+ d dist)
                   when (< next-dist (aref dists next))
                   do (setf (aref dists next) next-dist)
                      (heap-push (cons next-dist next) que)))
    dists))

(define-mod-operations +mod+)
(defconstant +nan+ most-negative-fixnum)
(defun make-dp (n src stages graph &optional reversed)
  (let ((stages (copy-seq stages))
        (res (make-array n :element-type 'uint31 :initial-element 0)))
    (with-cache (:array (100001) :element-type 'uint31 :initial-element #x7fffffff)
      (labels ((dp (v)
                 (cond ((= +nan+ (aref stages v)) 0)
                       ((= v src) 1)
                       (t (loop with res of-type uint31 = 0
                                for (prev . d) in (aref graph v)
                                do (when (if reversed
                                             (= (+ (aref stages v) d)
                                                (aref stages prev))
                                             (= (+ (aref stages prev) d)
                                                (aref stages v)))
                                     (incfmod res (dp prev)))
                                finally (return res))))))
        (dotimes (i n)
          (setf (aref res i) (dp i)))))
    res))
(defun main ()
  (let* ((n (read))
         (m (read))
         (ss (- (read) 1))
         (tt (- (read) 1))
         (graph (make-array n :element-type 'list :initial-element nil)))
    (dotimes (i m)
      (let ((u (- (read-fixnum) 1))
            (v (- (read-fixnum) 1))
            (d (read-fixnum)))
        (push (cons u d) (aref graph v))
        (push (cons v d) (aref graph u))))
    (let* ((dists+ (make-dists n m ss graph))
           (dists- (make-dists n m tt graph))
           (stages (make-array n
                               :element-type 'fixnum
                               :initial-element +nan+))
           (l (aref dists+ tt)))
      (assert (= (aref dists+ tt) (aref dists- ss)))
      (dotimes (i n)
        (when (= l (+ (aref dists+ i) (aref dists- i)))
          (setf (aref stages i) (aref dists+ i))))
      (let* ((dp+ (make-dp n ss stages graph nil))
             (dp- (make-dp n tt stages graph t))
             (res (* (aref dp+ tt) (aref dp- ss))))
        (assert (= (aref dp+ tt) (aref dp- ss)))
        (dotimes (i n)
          (unless (= +nan+ (aref stages i))
            (when (= (* 2 (aref stages i)) l)
              (decfmod res (mod* (aref dp+ i) (aref dp- i)
                                 (aref dp+ i) (aref dp- i))))
            (when (< (* 2 (aref stages i)) l)
              (loop for (next . d) in (aref graph i)
                    when (and (> (* 2 (aref stages next)) l)
                              (= (+ (aref stages i) d) (aref stages next)))
                    do (decfmod res (mod* (aref dp+ i) (aref dp- next)
                                          (aref dp+ i) (aref dp- next)))))))
        (println res)))))

#-swank (main)

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

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

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

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

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

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

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

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

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

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

Submitted source-code file size, in bytes.

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

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


(let ((a (parse-integer (remove #\space (read-line)))))
  (if (= a (expt (floor (sqrt a)) 2))
      (princ "Yes")
      (princ "No")))

Score : 200 points

Problem Statement

AtCoDeer the deer has found two positive integers, a and b.
Determine whether the concatenation of a and b in this order is a square number.

Constraints

1 ≤ a,b ≤ 100

a and b are integers.

Input

Input is given from Standard Input in the following format:

a b

Output

If the concatenation of a and b in this order is a square number, print Yes; otherwise, print No.

Sample Input 1

1 21

Sample Output 1

Yes

As 121 = 11 × 11, it is a square number.

Sample Input 2

100 100

Sample Output 2

No

100100 is not a square number.

Sample Input 3

12 10

Sample Output 3

No


(setq n (read) a (read) b (read))
(if (= 0 (mod (- b a) 2))
    (print "Alice"))
(if (= 1 (mod (- b a) 2))
    (print "Borys"))

Score : 300 points

Problem Statement

A game is played on a strip consisting of N cells consecutively numbered from 1 to N.

Alice has her token on cell A. Borys has his token on a different cell B.

Players take turns, Alice moves first.
The moving player must shift his or her token from its current cell X to the neighboring cell on the left, cell X-1, or on the right, cell X+1.
Note that it's disallowed to move the token outside the strip or to the cell with the other player's token.
In one turn, the token of the moving player must be shifted exactly once.

The player who can't make a move loses, and the other player wins.

Both players want to win. Who wins if they play optimally?

Constraints

2 \leq N \leq 100

1 \leq A < B \leq N

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print Alice if Alice wins, Borys if Borys wins, and Draw if nobody wins.

Sample Input 1

5 2 4

Sample Output 1

Alice

Alice can move her token to cell 3.
After that, Borys will be unable to move his token to cell 3, so he will have to move his token to cell 5.
Then, Alice moves her token to cell 4. Borys can't make a move and loses.

Sample Input 2

2 1 2

Sample Output 2

Borys

Alice can't make the very first move and loses.

Sample Input 3

58 23 42

Sample Output 3

Borys


Score : 100 points

Problem Statement

On some day in January 2018, Takaki is writing a document. The document has a column where the current date is written in yyyy/mm/dd format. For example, January 23, 2018 should be written as 2018/01/23.

After finishing the document, she noticed that she had mistakenly wrote 2017 at the beginning of the date column. Write a program that, when the string that Takaki wrote in the date column, S, is given as input, modifies the first four characters in S to 2018 and prints it.

Constraints

S is a string of length 10.

The first eight characters in S are 2017/01/.

The last two characters in S are digits and represent an integer between 1 and 31 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

Replace the first four characters in S with 2018 and print it.

Sample Input 1

2017/01/07

Sample Output 1

2018/01/07

Sample Input 2

2017/01/31

Sample Output 2

2018/01/31


(let ((str (read-line)))
  (setf (char str 3) #\8)
  (format t "~a~%" str))


(defun main ()
  (let* ((n (read))
         (ds (loop for i below n collect (read))))
    (format t "~A~%" (list-length (remove-duplicates ds)))))

(main)

Score : 200 points

Problem Statement

An X-layered kagami mochi (X ≥ 1) is a pile of X round mochi (rice cake) stacked vertically where each mochi (except the bottom one) has a smaller diameter than that of the mochi directly below it. For example, if you stack three mochi with diameters of 10, 8 and 6 centimeters from bottom to top in this order, you have a 3-layered kagami mochi; if you put just one mochi, you have a 1-layered kagami mochi.

Lunlun the dachshund has N round mochi, and the diameter of the i-th mochi is d_i centimeters. When we make a kagami mochi using some or all of them, at most how many layers can our kagami mochi have?

Constraints

1 ≤ N ≤ 100

1 ≤ d_i ≤ 100

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
d_1
:
d_N

Output

Print the maximum number of layers in a kagami mochi that can be made.

Sample Input 1

4
10
8
8
6

Sample Output 1

3

If we stack the mochi with diameters of 10, 8 and 6 centimeters from bottom to top in this order, we have a 3-layered kagami mochi, which is the maximum number of layers.

Sample Input 2

3
15
15
15

Sample Output 2

1

When all the mochi have the same diameter, we can only have a 1-layered kagami mochi.

Sample Input 3

7
50
30
50
100
50
80
30

Sample Output 3

4


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

(let* ((n (read))
	   (l (loop repeat n collect (read))))
  (princ (length (remove-duplicates l))))


Score : 100 points

Problem Statement

How many hours do we have until New Year at M o'clock (24-hour notation) on 30th, December?

Constraints

1≤M≤23

M is an integer.

Input

Input is given from Standard Input in the following format:

M

Output

If we have x hours until New Year at M o'clock on 30th, December, print x.

Sample Input 1

21

Sample Output 1

27

We have 27 hours until New Year at 21 o'clock on 30th, December.

Sample Input 2

12

Sample Output 2

36


(defvar A (read))
(defvar B (read))

(if (dotimes (x (+ 1 A B))
      (or (eq (= x A)
              (eq (read-char) #\-))
          (return t)))
    (princ "No")
    (princ "Yes") )

Score : 200 points

Problem Statement

The postal code in Atcoder Kingdom is A+B+1 characters long, its (A+1)-th character is a hyphen -, and the other characters are digits from 0 through 9.

You are given a string S. Determine whether it follows the postal code format in Atcoder Kingdom.

Constraints

1≤A,B≤5

|S|=A+B+1

S consists of - and digits from 0 through 9.

Input

Input is given from Standard Input in the following format:

A B
S

Output

Print Yes if S follows the postal code format in AtCoder Kingdom; print No otherwise.

Sample Input 1

3 4
269-6650

Sample Output 1

Yes

The (A+1)-th character of S is -, and the other characters are digits from 0 through 9, so it follows the format.

Sample Input 2

1 1
---

Sample Output 2

No

S contains unnecessary -s other than the (A+1)-th character, so it does not follow the format.

Sample Input 3

1 2
7444

Sample Output 3

No


(let ((x (read))
      (y (read))
      (str (read-line)))
  (multiple-value-bind (a b) (parse-integer str :junk-allowed t)
    (multiple-value-bind (c d) (parse-integer str :start (1+ b) :junk-allowed t)
      (if (and (= x b) (= y (- d 1 b)) a c)
          (princ "Yes")
          (princ "No")))))


;; -*- coding:utf-8 -*-

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter O3 '(optimize (speed 3) (safety 0) (debug 0)))
  (defparameter O2 '(optimize (speed 3) (safety 1))))

;; Hauptteil

(defmacro print-line (obj &optional (stream '*standard-output*))
  `(prog1 (princ ,obj ,stream) (terpri ,stream)))

(deftype unum nil '(integer 0 100000))
(defun make-eratosthenes (n)
  (declare #.O3
	   (unum n))
  (let ((max-idx (floor n 2))
	(arr (make-array (+ n 1) :element-type 'bit :initial-element 0)))
    (loop for factor from 3 to max-idx by 2 do
	 (loop for idx from (+ factor factor) to n by factor
	    do (setf (sbit arr idx) 1)))
    (loop for idx from 4 to n by 2
	 do (setf (sbit arr idx) 1))
    (setf (sbit arr 1) 1
	  (sbit arr 0) 1)
    arr))

(defparameter *erato-dict* (make-eratosthenes 100000))

(declaim (inline like-2017-p))
(defun like-2017-p (n)
  (declare (unum n))
  (and (zerop (sbit *erato-dict* n))
       (zerop (sbit *erato-dict* (ash (1+ n) -1)))))

(defun make-2017-dict (n)
  (declare #.O3
	   (unum n))
  (let ((arr (make-array (+ n 1) :element-type 'bit :initial-element 1)))
    (loop for idx from 1 to n by 2
       do (when (like-2017-p idx)
	    (setf (sbit arr idx) 0)))
    arr))

(defparameter *2017-dict* (make-2017-dict 100000))

(defmacro split-and-bind (arg-lst string &body body)
  (let ((pos1 (gensym "POS"))
	(pos2 (gensym "POS"))
	(str-fixed (gensym "STR")))
    (labels ((make-bind (arg-lst &optional (init-pos1 t))
	       (if (null arg-lst)
		   `(progn ,@body)
		   `(let* ((,pos1 ,(if init-pos1 0 `(1+ ,pos2)))
			   (,pos2 (position #\space ,str-fixed :start ,pos1 :test #'char=))
			   (,(car arg-lst) (parse-integer ,str-fixed :start ,pos1 :end ,pos2)))
		      ,(make-bind (cdr arg-lst) nil)))))
      `(let ((,str-fixed ,string))
	 ,(make-bind arg-lst)))))

(defun main ()
  (declare #.O3
   )
  (let* ((q (read))
	 (lefts (make-array q :element-type 'unum))
	 (rights (make-array q :element-type 'unum)))
    (dotimes (idx q)
      (split-and-bind (l r) (the string (read-line))
	(setf (aref lefts idx) l
	      (aref rights idx) r)))
    (dotimes (idx q)
      (print-line
       (loop for int from (aref lefts idx) to (aref rights idx) by 2
	  count (zerop (sbit *2017-dict* int)))))))

#-swank(main)

;; Für Test
(defun get-clipbrd ()
  (with-output-to-string (out)
    (run-program "C:/msys64/usr/bin/cat.exe" '("/dev/clipboard") :output out)))

(defun test ()
  (with-input-from-string (*standard-input* (delete #\return (get-clipbrd)))
    (main)))

;; Für Benchmark
(defparameter *file-path* *load-pathname*)
(defparameter *dat-path* (merge-pathnames "test.dat" *file-path*))

#+swank
(with-open-file (out *dat-path*
		     :direction :output :if-exists :supersede)
  )

(defun bench ()
  (let ((*standard-output* (make-broadcast-stream)))
    (with-open-file (*standard-input* *dat-path*)
      (time (main)))))

Score : 400 points

Problem Statement

We say that a odd number N is similar to 2017 when both N and (N+1)/2 are prime.

You are given Q queries.

In the i-th query, given two odd numbers l_i and r_i, find the number of odd numbers x similar to 2017 such that l_i ≤ x ≤ r_i.

Constraints

1≤Q≤10^5

1≤l_i≤r_i≤10^5

l_i and r_i are odd.

All input values are integers.

Input

Input is given from Standard Input in the following format:

Q
l_1 r_1
:
l_Q r_Q

Output

Print Q lines. The i-th line (1≤i≤Q) should contain the response to the i-th query.

Sample Input 1

1
3 7

Sample Output 1

2

3 is similar to 2017, since both 3 and (3+1)/2=2 are prime.

5 is similar to 2017, since both 5 and (5+1)/2=3 are prime.

7 is not similar to 2017, since (7+1)/2=4 is not prime, although 7 is prime.

Thus, the response to the first query should be 2.

Sample Input 2

4
13 13
7 11
7 11
2017 2017

Sample Output 2

1
0
0
1

Note that 2017 is also similar to 2017.

Sample Input 3

6
1 53
13 91
37 55
19 51
73 91
13 49

Sample Output 3

4
4
1
1
1
2


(defvar ab (+ (read) (read)))
(defvar cd (+ (read) (read)))

(cond
 ((> ab cd) (princ "Left"))
 ((< ab cd) (princ "Right"))
 (t (princ "Balanced")))

Score : 100 points

Problem Statement

A balance scale tips to the left if L>R, where L is the total weight of the masses on the left pan and R is the total weight of the masses on the right pan. Similarly, it balances if L=R, and tips to the right if L<R.

Takahashi placed a mass of weight A and a mass of weight B on the left pan of a balance scale, and placed a mass of weight C and a mass of weight D on the right pan.

Print Left if the balance scale tips to the left; print Balanced if it balances; print Right if it tips to the right.

Constraints

1\leq A,B,C,D \leq 10

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print Left if the balance scale tips to the left; print Balanced if it balances; print Right if it tips to the right.

Sample Input 1

3 8 7 1

Sample Output 1

Left

The total weight of the masses on the left pan is 11, and the total weight of the masses on the right pan is 8. Since 11>8, we should print Left.

Sample Input 2

3 4 5 2

Sample Output 2

Balanced

The total weight of the masses on the left pan is 7, and the total weight of the masses on the right pan is 7. Since 7=7, we should print Balanced.

Sample Input 3

1 7 6 4

Sample Output 3

Right

The total weight of the masses on the left pan is 8, and the total weight of the masses on the right pan is 10. Since 8<10, we should print Right.


(defun main ()
  (let* ((x (read))
	 (y (read))
	 (tmp x))
    (format t "~a~%"
	    (loop while (<= tmp y)
		  count (setf tmp (* 2 tmp))))))
(main)

Score : 300 points

Problem Statement

As a token of his gratitude, Takahashi has decided to give his mother an integer sequence.
The sequence A needs to satisfy the conditions below:

A consists of integers between X and Y (inclusive).

For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i.

Find the maximum possible length of the sequence.

Constraints

1 \leq X \leq Y \leq 10^{18}

All input values are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the maximum possible length of the sequence.

Sample Input 1

3 20

Sample Output 1

3

The sequence 3,6,18 satisfies the conditions.

Sample Input 2

25 100

Sample Output 2

3

Sample Input 3

314159265 358979323846264338

Sample Output 3

31


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

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

(defmacro println (obj &optional (stream '*standard-output*))
  `(let ((*read-default-float-format* 'double-float))
     (prog1 (princ ,obj ,stream) (terpri ,stream))))

(defconstant +mod+ 1000000007)

;; Body

(defun solve (s)
  (let ((res 0)
        (len (length s)))
    (loop with base = 0
          with base-c = (aref s base)
          for i below len
          do (unless (char= base-c (aref s i))
               (setf res (max res (min i (- len  base)))
                     base i
                     base-c (aref s i)))
          finally (setf res (max res (min i (- len base)))))
    res))

(defun main ()
  (let* ((s (read-line))
         (len (length s)))
    (println
     (max (solve s)
          (ceiling len 2)))))

#-swank(main)

Score : 500 points

Problem Statement

You are given a string S consisting of 0 and 1.
Find the maximum integer K not greater than |S| such that we can turn all the characters of S into 0 by repeating the following operation some number of times.

Choose a contiguous segment [l,r] in S whose length is at least K (that is, r-l+1\geq K must be satisfied). For each integer i such that l\leq i\leq r, do the following: if S_i is 0, replace it with 1; if S_i is 1, replace it with 0.

Constraints

1\leq |S|\leq 10^5

S_i(1\leq i\leq N) is either 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum integer K such that we can turn all the characters of S into 0 by repeating the operation some number of times.

Sample Input 1

010

Sample Output 1

2

We can turn all the characters of S into 0 by the following operations:

Perform the operation on the segment S[1,3] with length 3. S is now 101.

Perform the operation on the segment S[1,2] with length 2. S is now 011.

Perform the operation on the segment S[2,3] with length 2. S is now 000.

Sample Input 2

100000000

Sample Output 2

8

Sample Input 3

00001111

Sample Output 3

4


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) (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
;;;
;;; ARRAY-ELEMENT-TYPE is not constant-folded on SBCL version earlier than
;;; 1.5.0. See
;;; https://github.com/sbcl/sbcl/commit/9f0d12e7ab961828931d01c0b2a76a5885ad35d2
;;;

(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-c:deftransform array-element-type ((array))
    (let ((type (sb-c::lvar-type array)))
      (flet ((element-type (type)
               (and (sb-c::array-type-p type)
                    (sb-int:neq (sb-kernel::array-type-specialized-element-type type) sb-kernel:*wild-type*)
                    (sb-kernel:type-specifier (sb-kernel::array-type-specialized-element-type type)))))
        (cond ((let ((type (element-type type)))
                 (and type
                      `',type)))
              ((sb-kernel:union-type-p type)
               (let (result)
                 (loop for type in (sb-kernel:union-type-types type)
                       for et = (element-type type)
                       unless (and et
                                   (if result
                                       (equal result et)
                                       (setf result et)))
                       do (sb-c::give-up-ir1-transform))
                 `',result))
              ((sb-kernel:intersection-type-p type)
               (loop for type in (sb-kernel:intersection-type-types type)
                     for et = (element-type type)
                     when et
                     return `',et
                     finally (sb-c::give-up-ir1-transform)))
              (t
               (sb-c::give-up-ir1-transform)))))))

;;;
;;; Compute inversion number by merge sort
;;;

(declaim (inline %merge-count))
(defun %merge-count (l mid r source-vec dest-vec predicate key)
  (declare ((integer 0 #.array-total-size-limit) l mid r)
           (function predicate))
  (loop with count of-type (integer 0 #.most-positive-fixnum) = 0
        with i = l
        with j = mid
        for idx from l
        when (= i mid)
        do (loop for j from j below r
                 for idx from idx
                 do (setf (aref dest-vec idx)
                          (aref source-vec j))
                 finally (return-from %merge-count count))
        when (= j r)
        do (loop for i from i below mid
                 for idx from idx
                 do (setf (aref dest-vec idx)
                          (aref source-vec i))
                 finally (return-from %merge-count count))
        do (if (funcall predicate
                        (funcall key (aref source-vec j))
                        (funcall key (aref source-vec i)))
               (setf (aref dest-vec idx) (aref source-vec j)
                     j (1+ j)
                     count (+ count (- mid i)))
               (setf (aref dest-vec idx) (aref source-vec i)
                     i (1+ i)))))

(defmacro with-fixnum+ (form)
  (let ((fixnum+ '(integer 0 #.most-positive-fixnum)))
    `(the ,fixnum+
          ,(reduce (lambda (f1 f2)`(,(car form)
                                   (the ,fixnum+ ,f1)
                                   (the ,fixnum+ ,f2)))
	           (cdr form)))))

(declaim (inline %calc-by-insertion-sort!))
(defun %calc-by-insertion-sort! (vec predicate l r)
  (declare (function predicate)
           ((integer 0 #.array-total-size-limit) l r))
  (loop with inv-count of-type (integer 0 #.most-positive-fixnum) = 0
        for end from (+ l 1) below r
        do (loop for i from end above l
                 while (funcall predicate (aref vec i) (aref vec (- i 1)))
                 do (rotatef (aref vec (- i 1)) (aref vec i))
                    (incf inv-count))
        finally (return inv-count)))

;; NOTE: This function is slow on SBCL version earlier than 1.5.0 as
;; constant-folding of ARRAY-ELEMENT-TYPE doesn't work. Use
;; array-element-type.lisp if necessary.
(declaim (inline count-inversions!))
(defun count-inversions! (vector predicate &key (start 0) end (key #'identity))
  "Calculates the number of the inversions of VECTOR w.r.t. the strict order
PREDICATE. This function sorts VECTOR as a side effect."
  (declare (vector vector)
           (function predicate))
  (let ((end (or end (length vector))))
    (declare ((integer 0 #.array-total-size-limit) start end))
    (assert (<= start end))
    (let ((buffer (make-array end :element-type (array-element-type vector))))
      (labels
          ((recur (l r merge-to-vec1-p)
             (declare (optimize (safety 0))
                      ((integer 0 #.array-total-size-limit) l r))
             (cond ((= l r) 0)
                   ((= (+ l 1) r)
                    (unless merge-to-vec1-p
                      (setf (aref buffer l) (aref vector l)))
                    0)
                   ;; It is faster to use insertion sort. I don't adopt it
                   ;; by default, however, because that makes it hard to
                   ;; change the code to fit some special settings.
                   ;; ((and (<= (- r l) 24) merge-to-vec1-p)
                   ;;  (%calc-by-insertion-sort! vector predicate l r))
                   (t
                    (let ((mid (floor (+ l r) 2)))
                      (with-fixnum+
                          (+ (recur l mid (not merge-to-vec1-p))
                             (recur mid r (not merge-to-vec1-p))
                             (if merge-to-vec1-p
                                 (%merge-count l mid r buffer vector predicate key)
                                 (%merge-count l mid r vector buffer predicate key)))))))))
        (recur start end t)))))

(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 to-code))
(defun to-code (c)
  (- (char-code c) #.(char-code #\a)))

(declaim (inline make-histogram))
(defun make-histogram (s)
  (let ((res (make-array 26 :element-type 'uint32 :initial-element 0)))
    (sb-int:dovector (c s res)
      (incf (aref res (to-code c))))))

(defmacro return-the (type function)
  (let ((x (gensym)))
    `(lambda (,x)
       (the ,type (funcall ,function ,x)))))

(defun solve (s &optional (odd-char #\Nul))
  (declare (simple-base-string s))
  (let* ((len (length s))
         (len/2-floor (floor len 2))
         (len/2-ceil (ceiling len 2))
         (histo (make-histogram s))
         (current-histo (make-array 26 :element-type 'uint32 :initial-element 0))
         (seq (make-array len))
         (res 0))
    (declare (uint62 res))
    (let ((part1-ord 0)
          (part2-ord len/2-ceil))
      (declare (uint32 part1-ord part2-ord))
      (dotimes (i len)
        (let* ((c (aref s i))
               (code (to-code c)))
          (cond
            ((and (char= odd-char c)
                  (= (aref current-histo code) (floor (aref histo code) 2)))
             (setf (aref seq i) (cons c len/2-floor)))
            ((< (aref current-histo code) (floor (aref histo code) 2))
             (setf (aref seq i) (cons c part1-ord)
                   part1-ord (+ 1 part1-ord)))
            (t
             (setf (aref seq i) (cons c part2-ord)
                   part2-ord (+ 1 part2-ord))))
          (incf (aref current-histo code)))))
    (incf res (count-inversions! seq #'< :key (return-the uint32 #'cdr)))
    (let ((ords (make-array 26 :element-type 'list :initial-element nil)))
      (loop for i from (- len 1) downto len/2-ceil
            for ord from 0 below len/2-floor
            do (push ord (aref ords (to-code (car (aref seq i))))))
      (dotimes (i 26)
        (setf (aref ords i) (nreverse (aref ords i))))
      (let ((seq (subseq seq 0 len/2-floor)))
        (dotimes (i len/2-floor)
          (let ((c (car (aref seq i))))
            (setf (aref seq i) (cons c (pop (aref ords (to-code c)))))))
        (incf res (count-inversions! seq #'< :key (return-the uint32 #'cdr)))))
    res))

(defun main ()
  (let* ((s (coerce (read-line) 'simple-base-string))
         (len (length s))
         (histo (make-histogram s)))
    (println
     (if (evenp len)
         (if (every #'evenp histo)
             (solve s)
             -1)
         (let ((odd-chars (loop for i below 26
                                for x across histo
                                when (oddp x)
                                collect (code-char (+ 97 i)))))
           (if (= (length odd-chars) 1)
               (solve s (car odd-chars))
               -1))))))

#-swank (main)

Score : 800 points

Problem Statement

You are given a string S consisting of lowercase English letters.
Determine whether we can turn S into a palindrome by repeating the operation of swapping two adjacent characters. If it is possible, find the minimum required number of operations.

Constraints

1 \leq |S| \leq 2 × 10^5

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If we cannot turn S into a palindrome, print -1. Otherwise, print the minimum required number of operations.

Sample Input 1

eel

Sample Output 1

1

We can turn S into a palindrome by the following operation:

Swap the 2-nd and 3-rd characters. S is now ele.

Sample Input 2

ataatmma

Sample Output 2

4

We can turn S into a palindrome by the following operation:

Swap the 5-th and 6-th characters. S is now ataamtma.

Swap the 4-th and 5-th characters. S is now atamatma.

Swap the 3-rd and 4-th characters. S is now atmaatma.

Swap the 2-nd and 3-rd characters. S is now amtaatma.

Sample Input 3

snuke

Sample Output 3

-1

We cannot turn S into a palindrome.


(setq a (read))
(setq b (read))

(write (ceiling (+ a b) 2))

Score : 100 points

Problem Statement

You are given two positive integers a and b.
Let x be the average of a and b.
Print x rounded up to the nearest integer.

Constraints

a and b are integers.

1 \leq a, b \leq 100

Input

Input is given from Standard Input in the following format:

a b

Output

Print x rounded up to the nearest integer.

Sample Input 1

1 3

Sample Output 1

2

The average of 1 and 3 is 2.0, and it will be rounded up to the nearest integer, 2.

Sample Input 2

7 4

Sample Output 2

6

The average of 7 and 4 is 5.5, and it will be rounded up to the nearest integer, 6.

Sample Input 3

5 5

Sample Output 3

5


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

(let ((a (sort (read-line) #'char<))
	  (b (sort (read-line) #'char>)))
  (princ (if (string< a b)
		   "Yes"
		   "No")))

Score : 200 points

Problem Statement

You are given strings s and t, consisting of lowercase English letters.
You will create a string s' by freely rearranging the characters in s.
You will also create a string t' by freely rearranging the characters in t.
Determine whether it is possible to satisfy s' < t' for the lexicographic order.

Notes

For a string a = a_1 a_2 ... a_N of length N and a string b = b_1 b_2 ... b_M of length M, we say a < b for the lexicographic order if either one of the following two conditions holds true:

N < M and a_1 = b_1, a_2 = b_2, ..., a_N = b_N.

There exists i (1 \leq i \leq N, M) such that a_1 = b_1, a_2 = b_2, ..., a_{i - 1} = b_{i - 1} and a_i < b_i. Here, letters are compared using alphabetical order.

For example, xy < xya and atcoder < atlas.

Constraints

The lengths of s and t are between 1 and 100 (inclusive).

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If it is possible to satisfy s' < t', print Yes; if it is not, print No.

Sample Input 1

yx
axy

Sample Output 1

Yes

We can, for example, rearrange yx into xy and axy into yxa. Then, xy < yxa.

Sample Input 2

ratcode
atlas

Sample Output 2

Yes

We can, for example, rearrange ratcode into acdeort and atlas into tslaa. Then, acdeort < tslaa.

Sample Input 3

cd
abc

Sample Output 3

No

No matter how we rearrange cd and abc, we cannot achieve our objective.

Sample Input 4

w
ww

Sample Output 4

Yes

Sample Input 5

zzz
zzz

Sample Output 5

No


(let* ((n (read))
       (a (make-array n))
       (cnt (make-hash-table))
       (total 0))
  (dotimes (i n)
    (let ((ai (read)))
      (setf (aref a i) ai
            (gethash ai cnt) (1+ (gethash ai cnt 0)))))
  (maphash
    (lambda (key val)
      (if (< key val)
          (incf total (- val key))
          (when (> key val) (incf total val))))
    cnt)
  (format t "~A~%" total))

Score : 300 points

Problem Statement

You are given a sequence of positive integers of length N, a = (a_1, a_2, ..., a_N).
Your objective is to remove some of the elements in a so that a will be a good sequence.

Here, an sequence b is a good sequence when the following condition holds true:

For each element x in b, the value x occurs exactly x times in b.

For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.

Find the minimum number of elements that needs to be removed so that a will be a good sequence.

Constraints

1 \leq N \leq 10^5

a_i is an integer.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum number of elements that needs to be removed so that a will be a good sequence.

Sample Input 1

4
3 3 3 3

Sample Output 1

1

We can, for example, remove one occurrence of 3. Then, (3, 3, 3) is a good sequence.

Sample Input 2

5
2 4 1 4 2

Sample Output 2

2

We can, for example, remove two occurrences of 4. Then, (2, 1, 2) is a good sequence.

Sample Input 3

6
1 2 2 3 3 3

Sample Output 3

0

Sample Input 4

1
1000000000

Sample Output 4

1

Remove one occurrence of 10^9. Then, () is a good sequence.

Sample Input 5

8
2 7 1 8 2 8 1 8

Sample Output 5

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 (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* ((s (read-line))
         (len (length s))
         (x (read))
         (y (read))
         (hs (make-array len :element-type 'uint15 :fill-pointer 0))
         (vs (make-array len :element-type 'uint15 :fill-pointer 0)))
    (declare ((integer 1 8000) len)
             ((integer -8000 8000) x y))
    (loop with prev-t = -1
          with dest = hs
          for i below (length s)
          when (char= #\T (char s i))
          do (vector-push (- i prev-t 1) dest)
             (setq prev-t i
                   dest (if (eql dest hs) vs hs))
          finally (vector-push (- i prev-t 1) dest))
    (if
     (and
      (let ((dp1 (make-array (+ 1 (* 2 len)) :initial-element 0 :element-type 'bit))
            (dp2 (make-array (+ 1 (* 2 len)) :initial-element 0 :element-type 'bit)))
        (setf (aref dp1 (+ len (aref hs 0))) 1)
        (if (= 1 (length hs))
            (= (aref hs 0) x)
            (loop for h across (subseq hs 1)
                  for dp = dp1 then (if (eql dp dp1) dp2 dp1)
                  for dest-dp = dp2 then (if (eql dest-dp dp1) dp2 dp1)
                  do (fill dest-dp 0)
                     (loop for i below (length dp)
                           when (= 1 (aref dp i))
                           do (setf (aref dest-dp (+ i h)) 1
                                    (aref dest-dp (- i h)) 1))
                  finally (return (= 1 (aref dest-dp (+ len x)))))))
      (let ((dp1 (make-array (+ 1 (* 2 len)) :initial-element 0 :element-type 'bit))
            (dp2 (make-array (+ 1 (* 2 len)) :initial-element 0 :element-type 'bit)))
        (setf (aref dp1 len) 1)
        (if (zerop (length vs))
            (zerop y)
            (loop for v across vs
                  for dp = dp1 then (if (eql dp dp1) dp2 dp1)
                  for dest-dp = dp2 then (if (eql dest-dp dp1) dp2 dp1)
                  do (fill dest-dp 0)
                     (loop for i below (length dp)
                           when (= 1 (aref dp i))
                           do (setf (aref dest-dp (+ i v)) 1
                                    (aref dest-dp (- i v)) 1))
                  finally (return (= 1 (aref dest-dp (+ len y))))))))
     (write-line "Yes")
     (write-line "No"))))

#-swank(main)

Score : 500 points

Problem Statement

A robot is put at the origin in a two-dimensional plane.
Initially, the robot is facing in the positive x-axis direction.

This robot will be given an instruction sequence s.
s consists of the following two kinds of letters, and will be executed in order from front to back.

F : Move in the current direction by distance 1.

T : Turn 90 degrees, either clockwise or counterclockwise.

The objective of the robot is to be at coordinates (x, y) after all the instructions are executed.
Determine whether this objective is achievable.

Constraints

s consists of F and T.

1 \leq |s| \leq 8 000

x and y are integers.

|x|, |y| \leq |s|

Input

Input is given from Standard Input in the following format:

s
x y

Output

If the objective is achievable, print Yes; if it is not, print No.

Sample Input 1

FTFFTFFF
4 2

Sample Output 1

Yes

The objective can be achieved by, for example, turning counterclockwise in the first T and turning clockwise in the second T.

Sample Input 2

FTFFTFFF
-2 -2

Sample Output 2

Yes

The objective can be achieved by, for example, turning clockwise in the first T and turning clockwise in the second T.

Sample Input 3

FF
1 0

Sample Output 3

No

Sample Input 4

TF
1 0

Sample Output 4

No

Sample Input 5

FFTTFF
0 0

Sample Output 5

Yes

The objective can be achieved by, for example, turning counterclockwise in the first T and turning counterclockwise in the second T.

Sample Input 6

TTTT
1 0

Sample Output 6

No


(defun tsplit (s)
  (let ((n 0)
        (cnt (list)))
    (loop for c across s do
          (if (eq c #\F)
              (incf n)
              (progn
                (push n cnt)
                (setf n 0)))
          finally (if (< 0 n) (push n cnt)))
    (make-array (length cnt) :initial-contents (reverse cnt))))

(defun just (a b)
  (and (<= (abs a) b)
       (or (zerop (- b (abs a)))
           (evenp (- b (abs a))))))

(let* ((s (tsplit (read-line)))
       (slen (length s))
       (gx (- (read) (aref s 0)))
       (gy (read)))
  (format t "~A~%"
          (if (and (just gx (loop for i from 2 below slen by 2
                                  sum (aref s i)))
                   (just gy (loop for i from 1 below slen by 2
                                  sum (aref s i))))
              "Yes" "No")))


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

;; BEGIN_INSERTED_CONTENTS
;;;
;;; Trie
;;;

;; ASCII code:
;; #\A: 65
;; #\a: 97
;; #\0: 48
(declaim (inline trie-char-encode))
(defun trie-char-encode (x)
  (if (char= #\0 x) 0 1))

(defconstant +trie-alphabet-size+ 2)

;; TODO: enable to set VALUE to NIL by distinguishing null and unbound.
(declaim (inline %make-trie-node))
(defstruct (trie-node (:constructor %make-trie-node
                          (&optional value
                           &aux (children (make-array #.+trie-alphabet-size+
                                                      :element-type t
                                                      :initial-element 0)))))
  (value nil)
  (children nil :type (simple-array t (#.+trie-alphabet-size+))))

(declaim (inline make-trie))
(defun make-trie () (%make-trie-node))

(declaim (inline trie-add!))
(defun trie-add! (trie-node string &optional (value t))
  "Adds STRING to the trie and assigns VALUE to it. Note that null value means
the string doesn't exist in the trie: that is, (trie-add! <trie-node> <string>
nil) virtually works as a deletion of <string>."
  (declare (vector string))
  (let ((end (length string)))
    (labels ((recur (node position)
               (if (= position end)
                   (unless (trie-node-value node)
                     (setf (trie-node-value node) value))
                   (let ((children (trie-node-children node))
                         (char (trie-char-encode (aref string position))))
                     (when (eql 0 (aref children char))
                       (setf (aref children char) (%make-trie-node)))
                     (recur (aref children char) (+ 1 position))))))
      (recur trie-node 0)
      trie-node)))

(declaim (inline trie-query))
(defun trie-query (trie-node string function &key (start 0) end)
  "Calls FUNCTION for each prefix of STRING existing in TRIE-NODE. FUNCTION
takes two arguments: the end position and the assigned value."
  (declare (vector string)
           ((integer 0 #.most-positive-fixnum) start)
           ((or null (integer 0 #.most-positive-fixnum)) end)
           (function function))
  (let ((end (or end (length string))))
    (labels ((recur (node position)
               (when (trie-node-value node)
                 (funcall function position (trie-node-value node)))
               (unless (= position end)
                 (let ((children (trie-node-children node))
                       (char (trie-char-encode (aref string position))))
                   (unless (eql 0 (aref children char))
                     (recur (aref children char) (+ 1 position)))))))
      (recur trie-node start))))

(defun trie-get (trie-node string &key (start 0) end)
  "Finds STRING in TRIE-NODE and returns the assigned value if it exists,
  otherwise NIL."
  (declare (vector string)
           ((integer 0 #.most-positive-fixnum) start)
           ((or null (integer 0 #.most-positive-fixnum)) end))
  (let ((end (or end (length string))))
    (labels ((recur (node position)
               (if (= position end)
                   (trie-node-value node)
                   (let ((children (trie-node-children node))
                         (char (trie-char-encode (aref string position))))
                     (unless (eql 0 (aref children char))
                       (recur (aref children char) (+ 1 position)))))))
      (recur trie-node start))))

(defun trie-query-longest (trie-node string &key (start 0) end)
  "Returns the end position and the value of the longest word in TRIE-NODE which
coincides with a prefix of STRING. Returns NIL when no such words exist."
  (declare (vector string)
           ((integer 0 #.most-positive-fixnum) start)
           ((or null (integer 0 #.most-positive-fixnum)) end))
  (let ((end (or end (length string)))
        result-position
        result-value)
    (declare ((or null (integer 0 #.most-positive-fixnum)) result-position))
    (labels ((recur (node position)
               (when (trie-node-value node)
                 (setq result-position position
                       result-value (trie-node-value node)))
               (unless (= position end)
                 (let ((children (trie-node-children node))
                       (char (trie-char-encode (aref string position))))
                   (unless (eql 0 (aref children char))
                     (recur (aref children char) (+ 1 position)))))))
      (recur trie-node start)
      (values result-position result-value))))

(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 mex (&rest args)
  (let ((table (make-hash-table :test #'eq)))
    (dolist (x args)
      (setf (gethash x table) t))
    (loop for x of-type (integer 0 #.most-positive-fixnum) from 0
          unless (gethash x table)
          do (return x))))

(defun test (depth)
  (let ((seq (make-array (+ 1 depth) :element-type 'uint32)))
    (setf (aref seq depth) 0)
    (loop for d from (- depth 1) downto 0
          do (setf (aref seq d)
                   (apply #'mex
                          (cons 0
                                (loop for end from (+ d 2) to depth
                                      collect
                                         (loop with xor = 0
                                               for i from (+ d 1) below end
                                               do (setf xor (logxor xor (aref seq i)))
                                               finally (return xor)))))))
    seq))

(declaim (inline grundy))
(defun grundy (depth max-depth)
  (declare (uint62 depth max-depth))
  (if (= depth max-depth)
      0
      (let ((x (- max-depth depth))
            (res 1))
        (declare (uint62 x res))
        (loop while (evenp x)
              do (setf res (* res 2))
                 (setf x (floor x 2)))
        res)))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (l (read))
         (trie (make-trie))
         (res 0))
    (declare (uint62 n l res))
    (dotimes (i n)
      (trie-add! trie (the simple-string (read-line))))
    (labels ((dfs (node depth)
               (declare (uint62 depth))
               (if (eql 0 node)
                   (setq res (logxor res (grundy (- depth 1) l)))
                   (let ((children (trie-node-children node)))
                     (dfs (aref children 0) (+ depth 1))
                     (dfs (aref children 1) (+ depth 1))))))
      (dfs trie 0)
      (if (zerop res)
          (write-line "Bob")
          (write-line "Alice")))))

#-swank (main)

Score : 700 points

Problem Statement

For strings s and t, we will say that s and t are prefix-free when neither is a prefix of the other.

Let L be a positive integer. A set of strings S is a good string set when the following conditions hold true:

Each string in S has a length between 1 and L (inclusive) and consists of the characters 0 and 1.

Any two distinct strings in S are prefix-free.

We have a good string set S = \{ s_1, s_2, ..., s_N \}. Alice and Bob will play a game against each other. They will alternately perform the following operation, starting from Alice:

Add a new string to S. After addition, S must still be a good string set.

The first player who becomes unable to perform the operation loses the game. Determine the winner of the game when both players play optimally.

Constraints

1 \leq N \leq 10^5

1 \leq L \leq 10^{18}

s_1, s_2, ..., s_N are all distinct.

{ s_1, s_2, ..., s_N } is a good string set.

|s_1| + |s_2| + ... + |s_N| \leq 10^5

Input

Input is given from Standard Input in the following format:

N L
s_1
s_2
:
s_N

Output

If Alice will win, print Alice; if Bob will win, print Bob.

Sample Input 1

2 2
00
01

Sample Output 1

Alice

If Alice adds 1, Bob will be unable to add a new string.

Sample Input 2

2 2
00
11

Sample Output 2

Bob

There are two strings that Alice can add on the first turn: 01 and 10.
In case she adds 01, if Bob add 10, she will be unable to add a new string.
Also, in case she adds 10, if Bob add 01, she will be unable to add a new string.

Sample Input 3

3 3
0
10
110

Sample Output 3

Alice

If Alice adds 111, Bob will be unable to add a new string.

Sample Input 4

2 1
0
1

Sample Output 4

Bob

Alice is unable to add a new string on the first turn.

Sample Input 5

1 2
11

Sample Output 5

Alice

Sample Input 6

2 3
101
11

Sample Output 6

Bob


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

;; BEGIN_INSERTED_CONTENTS
;;;
;;; Trie
;;;

;; ASCII code:
;; #\A: 65
;; #\a: 97
;; #\0: 48
(declaim (inline trie-char-encode))
(defun trie-char-encode (x)
  (if (char= #\0 x) 0 1))

(defconstant +trie-alphabet-size+ 2)

;; TODO: enable to set VALUE to NIL by distinguishing null and unbound.
(declaim (inline %make-trie-node))
(defstruct (trie-node (:constructor %make-trie-node
                          (&optional value
                           &aux (children (make-array #.+trie-alphabet-size+
                                                      :element-type t
                                                      :initial-element 0)))))
  (value nil)
  (children nil :type (simple-array t (#.+trie-alphabet-size+))))

(declaim (inline make-trie))
(defun make-trie () (%make-trie-node))

(declaim (inline trie-add!))
(defun trie-add! (trie-node string &optional (value t))
  "Adds STRING to the trie and assigns VALUE to it. Note that null value means
the string doesn't exist in the trie: that is, (trie-add! <trie-node> <string>
nil) virtually works as a deletion of <string>."
  (declare (vector string))
  (let ((end (length string)))
    (labels ((recur (node position)
               (if (= position end)
                   (unless (trie-node-value node)
                     (setf (trie-node-value node) value))
                   (let ((children (trie-node-children node))
                         (char (trie-char-encode (aref string position))))
                     (when (eql 0 (aref children char))
                       (setf (aref children char) (%make-trie-node)))
                     (recur (aref children char) (+ 1 position))))))
      (recur trie-node 0)
      trie-node)))

(declaim (inline trie-query))
(defun trie-query (trie-node string function &key (start 0) end)
  "Calls FUNCTION for each prefix of STRING existing in TRIE-NODE. FUNCTION
takes two arguments: the end position and the assigned value."
  (declare (vector string)
           ((integer 0 #.most-positive-fixnum) start)
           ((or null (integer 0 #.most-positive-fixnum)) end)
           (function function))
  (let ((end (or end (length string))))
    (labels ((recur (node position)
               (when (trie-node-value node)
                 (funcall function position (trie-node-value node)))
               (unless (= position end)
                 (let ((children (trie-node-children node))
                       (char (trie-char-encode (aref string position))))
                   (unless (eql 0 (aref children char))
                     (recur (aref children char) (+ 1 position)))))))
      (recur trie-node start))))

(defun trie-get (trie-node string &key (start 0) end)
  "Finds STRING in TRIE-NODE and returns the assigned value if it exists,
  otherwise NIL."
  (declare (vector string)
           ((integer 0 #.most-positive-fixnum) start)
           ((or null (integer 0 #.most-positive-fixnum)) end))
  (let ((end (or end (length string))))
    (labels ((recur (node position)
               (if (= position end)
                   (trie-node-value node)
                   (let ((children (trie-node-children node))
                         (char (trie-char-encode (aref string position))))
                     (unless (eql 0 (aref children char))
                       (recur (aref children char) (+ 1 position)))))))
      (recur trie-node start))))

(defun trie-query-longest (trie-node string &key (start 0) end)
  "Returns the end position and the value of the longest word in TRIE-NODE which
coincides with a prefix of STRING. Returns NIL when no such words exist."
  (declare (vector string)
           ((integer 0 #.most-positive-fixnum) start)
           ((or null (integer 0 #.most-positive-fixnum)) end))
  (let ((end (or end (length string)))
        result-position
        result-value)
    (declare ((or null (integer 0 #.most-positive-fixnum)) result-position))
    (labels ((recur (node position)
               (when (trie-node-value node)
                 (setq result-position position
                       result-value (trie-node-value node)))
               (unless (= position end)
                 (let ((children (trie-node-children node))
                       (char (trie-char-encode (aref string position))))
                   (unless (eql 0 (aref children char))
                     (recur (aref children char) (+ 1 position)))))))
      (recur trie-node start)
      (values result-position result-value))))

(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 mex (&rest args)
  (let ((table (make-hash-table :test #'eq)))
    (dolist (x args)
      (setf (gethash x table) t))
    (loop for x of-type (integer 0 #.most-positive-fixnum) from 0
          unless (gethash x table)
          do (return x))))

(defun test (depth)
  (let ((seq (make-array (+ 1 depth) :element-type 'uint32)))
    (setf (aref seq depth) 0)
    (loop for d from (- depth 1) downto 0
          do (setf (aref seq d)
                   (apply #'mex
                          (cons 0
                                (loop for end from (+ d 2) to depth
                                      collect
                                         (loop with xor = 0
                                               for i from (+ d 1) below end
                                               do (setf xor (logxor xor (aref seq i)))
                                               finally (return xor)))))))
    seq))

(declaim (inline grundy))
(defun grundy (depth max-depth)
  (assert (<= 0 depth max-depth))
  (if (= depth max-depth)
      0
      (let ((x (- max-depth depth))
            (res 1))
        (declare (uint62 x res))
        (loop while (evenp x)
              do (setf res (* res 2))
                 (setf x (floor x 2)))
        res)))

(defun main ()
  (let* ((n (read))
         (l (read))
         (trie (make-trie))
         (grundys (test l))
         (res 0))
    (declare (uint62 n l res))
    (dotimes (i n)
      (trie-add! trie (the simple-string (read-line))))
    #>grundys
    (labels ((dfs (node depth)
               (declare (uint62 depth))
               (if (eql 0 node)
                   (setq res (logxor res (grundy (- depth 1) l)))
                   (let ((children (trie-node-children node)))
                     (dfs (aref children 0) (+ depth 1))
                     (dfs (aref children 1) (+ depth 1))))))
      (dfs trie 0)
      (if (zerop res)
          (write-line "Bob")
          (write-line "Alice")))))

#-swank (main)