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

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

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

     (sb-c:define-source-transform mod* (&rest args)
       (if (null args)
           1
           (reduce (lambda (x y) `(mod (* ,x ,y) ,',divisor)) args)))

     (defun mod+ (&rest args)
       (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)))))

;;;
;;; Binomial coefficient with mod
;;; build: O(n)
;;; query: O(1)
;;;

;; TODO: non-global handling

(defconstant +binom-size+ 110000)
(defconstant +binom-mod+ #.(+ (expt 10 9) 7))

(declaim ((simple-array (unsigned-byte 32) (*)) *fact* *fact-inv* *inv*))
(defparameter *fact* (make-array +binom-size+ :element-type '(unsigned-byte 32))
  "table of factorials")
(defparameter *fact-inv* (make-array +binom-size+ :element-type '(unsigned-byte 32))
  "table of inverses of factorials")
(defparameter *inv* (make-array +binom-size+ :element-type '(unsigned-byte 32))
  "table of inverses of non-negative integers")

(defun initialize-binom ()
  (declare (optimize (speed 3) (safety 0)))
  (setf (aref *fact* 0) 1
        (aref *fact* 1) 1
        (aref *fact-inv* 0) 1
        (aref *fact-inv* 1) 1
        (aref *inv* 1) 1)
  (loop for i from 2 below +binom-size+
        do (setf (aref *fact* i) (mod (* i (aref *fact* (- i 1))) +binom-mod+)
                 (aref *inv* i) (- +binom-mod+
                                   (mod (* (aref *inv* (rem +binom-mod+ i))
                                           (floor +binom-mod+ i))
                                        +binom-mod+))
                 (aref *fact-inv* i) (mod (* (aref *inv* i)
                                             (aref *fact-inv* (- i 1)))
                                          +binom-mod+))))

(initialize-binom)

(declaim (inline binom))
(defun binom (n k)
  "Returns nCk."
  (if (or (< n k) (< n 0) (< k 0))
      0
      (mod (* (aref *fact* n)
              (mod (* (aref *fact-inv* k) (aref *fact-inv* (- n k))) +binom-mod+))
           +binom-mod+)))

(declaim (inline perm))
(defun perm (n k)
  "Returns nPk."
  (if (or (< n k) (< n 0) (< k 0))
      0
      (mod (* (aref *fact* n) (aref *fact-inv* (- n k))) +binom-mod+)))

;; TODO: compiler macro or source-transform
(declaim (inline multinomial))
(defun multinomial (&rest ks)
  "Returns the multinomial coefficient K!/k_1!k_2!...k_n! for K = k_1 + k_2 +
... + k_n. K must be equal to or smaller than
MOST-POSITIVE-FIXNUM. (multinomial) returns 1."
  (let ((sum 0)
        (result 1))
    (declare ((integer 0 #.most-positive-fixnum) result sum))
    (dolist (k ks)
      (incf sum k)
      (setq result
            (mod (* result (aref *fact-inv* k)) +binom-mod+)))
    (mod (* result (aref *fact* sum)) +binom-mod+)))

(declaim (inline catalan))
(defun catalan (n)
  "Returns the N-th Catalan number."
  (declare ((integer 0 #.most-positive-fixnum) n))
  (mod (* (aref *fact* (* 2 n))
          (mod (* (aref *fact-inv* (+ n 1))
                  (aref *fact-inv* n))
               +binom-mod+))
       +binom-mod+))

(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 #\-))
                                  (setf minus t)))))))
      (declare ((integer 0 #.most-positive-fixnum) result))
      (loop
        (let* ((byte (%read-byte)))
          (if (<= 48 byte 57)
              (setq result (+ (- byte 48)
                              (* 10 (the (integer 0 #.(floor most-positive-fixnum 10))
                                         result))))
              (return (if minus (- result) result))))))))

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(define-mod-operations +mod+)

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (as (make-array n :element-type 'uint31))
         (res 0)
         (factor 0)
         (l 1)
         (r n))
    (declare (uint31 n res factor l r))
    (dotimes (i n)
      (setf (aref as i) (read-fixnum)))
    (dotimes (i n)
      (if (zerop i)
          (loop for i from 1 to n
                do (incfmod factor (aref *inv* i)))
          (progn
            (decfmod factor (aref *inv* r))
            (decf r)
            (incf l)
            (incfmod factor (aref *inv* l))))
      (incfmod res (mod* (aref *fact* n)
                         (aref as i)
                         factor)))
    (println res)))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
1 2
"
    "9
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4
1 1 1 1
"
    "212
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "10
1 2 4 8 16 32 64 128 256 512
"
    "880971923
")))

Score : 600 points

Problem Statement

There are N blocks arranged in a row, numbered 1 to N from left to right.
Each block has a weight, and the weight of Block i is A_i.
Snuke will perform the following operation on these blocks N times:

Choose one block that is still not removed, and remove it.
The cost of this operation is the sum of the weights of the blocks that are connected to the block being removed (including itself).
Here, two blocks x and y ( x \leq y ) are connected when, for all z ( x \leq z \leq y ), Block z is still not removed.

There are N! possible orders in which Snuke removes the blocks.
For all of those N! orders, find the total cost of the N operations, and calculate the sum of those N! total costs.
As the answer can be extremely large, compute the sum modulo 10^9+7.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

For all of the N! orders, find the total cost of the N operations, and print the sum of those N! total costs, modulo 10^9+7.

Sample Input 1

2
1 2

Sample Output 1

9

First, we will consider the order "Block 1 -> Block 2".
In the first operation, the cost of the operation is 1+2=3, as Block 1 and 2 are connected.
In the second operation, the cost of the operation is 2, as only Block 2 remains.
Thus, the total cost of the two operations for this order is 3+2=5.

Then, we will consider the order "Block 2 -> Block 1".
In the first operation, the cost of the operation is 1+2=3, as Block 1 and 2 are connected.
In the second operation, the cost of the operation is 1, as only Block 1 remains.
Thus, the total cost of the two operations for this order is 3+1=4.

Therefore, the answer is 5+4=9.

Sample Input 2

4
1 1 1 1

Sample Output 2

212

Sample Input 3

10
1 2 4 8 16 32 64 128 256 512

Sample Output 3

880971923


#-swank
(unless (member :child-sbcl *features*)
  "I refered from https://competitive12.blogspot.com/2020/03/common-lisp.html thank you!"
  (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))))
#-swank
(unless (member :child-sbcl *features*)
  "I refered from https://competitive12.blogspot.com/2020/03/common-lisp.html thank you!"
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "256MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))
(defmacro dp (name args memo-size &body body)
  (let ((memo (gensym)))
    `(let ((,memo (make-array ,memo-size :initial-element nil)))
       (defun ,name ,args
         (or (aref ,memo ,@args)
             (setf (aref ,memo ,@args)
                   ,@body))))))

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

(defmacro collect-times (time body)
  `(loop repeat ,time collect ,body))

(defun read-times (time)
  (collect-times time (read)))

(defmacro aif (expr then else)
  `(let ((it ,expr))
     (if it ,then ,else)))

(defmacro awhen (expr &rest then)
  `(aif ,expr (progn ,@then) nil))

(defun comulative (function list &key base)
  (if base
      (comulative function (cons base list))
      (do ((lst (cdr list) (cdr lst))
           (acc (list (car list))))
          ((null lst) (reverse acc))
        (push (funcall function (car acc) (car lst)) acc))))

(defun binary-search (function left right
                      &optional
                        (eps 1)
                        (average-function (lambda (x y) (ash (+ x y) -1))))
  (if (<= (abs (- left right)) eps)
      right
      (let ((mid (funcall average-function left right)))
        (if (funcall function mid)
            (binary-search function left mid eps average-function)
            (binary-search function mid right eps average-function)))))

(defun arithmetic-mean (&rest body)
  (/ (apply #'+ body) (length body)))

(defvar +MOD+ (+ (expt 10 9) 7))

(defun range-0-n (n &optional (step 1))
  (loop for i from 0 below n by step collect i))

(defun range-1-n (n &optional (step 1))
  (loop for i from 1 below n by step collect i))

(defun range-a-b (a b &optional (step 1))
  (loop for i from a below b by step collect i))

(defun map-0-n (function n &optional (step 1))
  (mapcar function (range-0-n n step)))

(defun map-1-n (function n &optional (step 1))
  (mapcar function (range-1-n n step)))

(defun map-a-b (function a b &optional (step 1))
  (mapcar function (range-a-b a b step)))

(defun read-string (&optional (stream *standard-input*))
  (labels ((is-empty (x)
             (or (char= x #\space) (char= x #\newline))))
    (loop for char = (read-char stream)
          with result
          when (and result (is-empty char))
            do (return (concatenate 'string (nreverse result)))
          when (null (is-empty char))
            do (push char result))))

(defun merge-sort (lst &optional (compare #'<))
  (let ((turn 0))
    (labels ((merge-list (a b a-length b-length)
               (cond ((zerop a-length) b)
                     ((zerop b-length) a)
                     ((funcall compare (car b) (car a))
                      (incf turn a-length)
                      (cons (car b)
                            (merge-list a (cdr b) a-length (1- b-length))))
                     (t
                      (cons (car a)
                            (merge-list (cdr a) b (1- a-length) b-length)))))
             (f (lst length)
               (if (= length 1)
                   lst
                   (let ((mid (ash length -1)))
                     (merge-list (f (subseq lst 0 mid) mid)
                                 (f (subseq lst mid) (- length mid))
                                 mid
                                 (- length mid))))))
      (values (f lst (length lst)) turn))))

(defun group (lst &optional (test #'eql) (key nil))
  (let ((table (make-hash-table :test test)))
    (mapc (lambda (x)
            (push x (gethash (if key (funcall key x) x) table)))
          lst)
    (loop for value being each hash-value in table
          collect value)))

(defun nearby (&rest args)
  (let ((current (subseq args 0 (ash (length args) -1)))
        (validator (subseq args (ash (length args) -1)))
        (res nil))
    (labels ((check ()
               (every (lambda (x y) (and (<= 0 x) (< x y)))
                      current validator))
             (f (lst)
               (unless lst (return-from f))
               (let ((x (car lst)))
                 (setf (car lst) (1+ x))
                 (when (check) (push (copy-list current) res))
                 (setf (car lst) (1- x))
                 (when (check) (push (copy-list current) res))
                 (setf (car lst) x))
               (f (cdr lst))))
      (f current)
      res)))

(defun main (limit line)
  (let ((validated (remove-if (lambda (x) (> (cdr x) limit)) line)))
    (if validated
        (reduce #'min validated :key #'car)
        "TLE")))

(let ((n (read))
      (limit (read)))
  (princ (main limit (collect-times n (cons (read) (read))))))

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

Score : 200 points

Problem Statement

When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC.

You, the smartwatch, has found N routes to his home.

If Mr. X uses the i-th of these routes, he will get home in time t_i at cost c_i.

Find the smallest cost of a route that takes not longer than time T.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq T \leq 1000

1 \leq c_i \leq 1000

1 \leq t_i \leq 1000

The pairs (c_i, t_i) are distinct.

Input

Input is given from Standard Input in the following format:

N T
c_1 t_1
c_2 t_2
:
c_N t_N

Output

Print the smallest cost of a route that takes not longer than time T.

If there is no route that takes not longer than time T, print TLE instead.

Sample Input 1

3 70
7 60
1 80
4 50

Sample Output 1

4

The first route gets him home at cost 7.

The second route takes longer than time T = 70.

The third route gets him home at cost 4.

Thus, the cost 4 of the third route is the minimum.

Sample Input 2

4 3
1 1000
2 4
3 1000
4 500

Sample Output 2

TLE

There is no route that takes not longer than time T = 3.

Sample Input 3

5 9
25 8
5 9
4 10
1000 1000
6 1

Sample Output 3

5

Submitted source-code file size, in bytes.

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

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


(defun solve (n ans tmax)
  (cond
    ((< n 1)
     (if (> ans 1000) 'tle ans))
    (t
     (let ((cost (read)) (time (read)))
	 (if (and
	      (<= time tmax)
	      (< cost ans))
	     (solve (- n 1) cost tmax)
	     (solve (- n 1) ans tmax))))))
(print (solve (read) 1000000000 (read)))


(defun main ()
  (let ((N (read))
        (Time (read))
        (lst (list nil)))
    (dotimes (x N)
      (let ((a (read))
            (b (read)))
        (when (<= b Time)
          (push a lst))))
    (setq lst (sort (cdr (reverse lst)) #'<))
    (let ((ans (nth 0 lst)))
      (if (null ans)
          (princ "TLE")
          (princ ans)))))

(main)


(defparameter *n* (read))
(defparameter *t* (read))
(defparameter *c-t* (loop repeat *n*
                          collect (cons (read) (read))))

(defun f (c-t tt)
  (let ((alst (mapcar #'car
                      (remove-if-not (lambda (pair) (>= tt (cdr pair)))
                                     c-t))))
    (if alst
        (reduce #'min alst)
        "TLE")))

(princ (f *c-t* *t*))


(defun f (x)
  (cond
    ((equal x #\1) (prin1 9))
    ((equal x #\9) (prin1 1))
    (t (prin1 x))))

(loop for i across (read-line)
     collect (f i))

Score : 100 points

Problem Statement

Cat Snuke is learning to write characters.
Today, he practiced writing digits 1 and 9, but he did it the other way around.

You are given a three-digit integer n written by Snuke.
Print the integer obtained by replacing each digit 1 with 9 and each digit 9 with 1 in n.

Constraints

111 \leq n \leq 999

n is an integer consisting of digits 1 and 9.

Input

Input is given from Standard Input in the following format:

n

Output

Print the integer obtained by replacing each occurrence of 1 with 9 and each occurrence of 9 with 1 in n.

Sample Input 1

119

Sample Output 1

991

Replace the 9 in the ones place with 1, the 1 in the tens place with 9 and the 1 in the hundreds place with 9. The answer is 991.

Sample Input 2

999

Sample Output 2

111


(let ((s (read-line)))
  (loop for i across s do
    (format t "~A" (if (equal i #\9) 1 9)))
  (format t "~%"))


#-swank
(unless (member :child-sbcl *features*)
  "I refered from https://competitive12.blogspot.com/2020/03/common-lisp.html thank you!"
  (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))))
#-swank
(unless (member :child-sbcl *features*)
  "I refered from https://competitive12.blogspot.com/2020/03/common-lisp.html thank you!"
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "256MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))
(defmacro dp (name args memo-size &body body)
  (let ((memo (gensym)))
    `(let ((,memo (make-array ,memo-size :initial-element nil)))
       (defun ,name ,args
         (or (aref ,memo ,@args)
             (setf (aref ,memo ,@args)
                   ,@body))))))

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

(defmacro collect-times (time body)
  `(loop repeat ,time collect ,body))

(defun read-times (time)
  (collect-times time (read)))

(defmacro aif (expr then else)
  `(let ((it ,expr))
     (if it ,then ,else)))

(defmacro awhen (expr &rest then)
  `(aif ,expr (progn ,@then) nil))

(defun comulative (function list &key base)
  (if base
      (comulative function (cons base list))
      (do ((lst (cdr list) (cdr lst))
           (acc (list (car list))))
          ((null lst) (reverse acc))
        (push (funcall function (car acc) (car lst)) acc))))

(defun binary-search (function left right
                      &optional
                        (eps 1)
                        (average-function (lambda (x y) (ash (+ x y) -1))))
  (if (<= (abs (- left right)) eps)
      right
      (let ((mid (funcall average-function left right)))
        (if (funcall function mid)
            (binary-search function left mid eps average-function)
            (binary-search function mid right eps average-function)))))

(defun arithmetic-mean (&rest body)
  (/ (apply #'+ body) (length body)))

(defvar +MOD+ (+ (expt 10 9) 7))

(defun range-0-n (n &optional (step 1))
  (loop for i from 0 below n by step collect i))

(defun range-1-n (n &optional (step 1))
  (loop for i from 1 below n by step collect i))

(defun range-a-b (a b &optional (step 1))
  (loop for i from a below b by step collect i))

(defun map-0-n (function n &optional (step 1))
  (mapcar function (range-0-n n step)))

(defun map-1-n (function n &optional (step 1))
  (mapcar function (range-1-n n step)))

(defun map-a-b (function a b &optional (step 1))
  (mapcar function (range-a-b a b step)))

(defun read-string (&optional (stream *standard-input*))
  (labels ((is-empty (x)
             (or (char= x #\space) (char= x #\newline))))
    (loop for char = (read-char stream)
          with result
          when (and result (is-empty char))
            do (return (concatenate 'string (nreverse result)))
          when (null (is-empty char))
            do (push char result))))

(defun merge-sort (lst &optional (compare #'<))
  (let ((turn 0))
    (labels ((merge-list (a b a-length b-length)
               (cond ((zerop a-length) b)
                     ((zerop b-length) a)
                     ((funcall compare (car b) (car a))
                      (incf turn a-length)
                      (cons (car b)
                            (merge-list a (cdr b) a-length (1- b-length))))
                     (t
                      (cons (car a)
                            (merge-list (cdr a) b (1- a-length) b-length)))))
             (f (lst length)
               (if (= length 1)
                   lst
                   (let ((mid (ash length -1)))
                     (merge-list (f (subseq lst 0 mid) mid)
                                 (f (subseq lst mid) (- length mid))
                                 mid
                                 (- length mid))))))
      (values (f lst (length lst)) turn))))

(defun group (lst &optional (test #'eql) (key nil))
  (let ((table (make-hash-table :test test)))
    (mapc (lambda (x)
            (push x (gethash (if key (funcall key x) x) table)))
          lst)
    (loop for value being each hash-value in table
          collect value)))

(defun nearby (&rest args)
  (let ((current (subseq args 0 (ash (length args) -1)))
        (validator (subseq args (ash (length args) -1)))
        (res nil))
    (labels ((check ()
               (every (lambda (x y) (and (<= 0 x) (< x y)))
                      current validator))
             (f (lst)
               (unless lst (return-from f))
               (let ((x (car lst)))
                 (setf (car lst) (1+ x))
                 (when (check) (push (copy-list current) res))
                 (setf (car lst) (1- x))
                 (when (check) (push (copy-list current) res))
                 (setf (car lst) x))
               (f (cdr lst))))
      (f current)
      res)))

(defun main (n &optional (x 111))
  (if (<= n x)
      x
      (main n (+ x 111))))

(princ (main (read)))

Score : 200 points

Problem Statement

Kurohashi has never participated in AtCoder Beginner Contest (ABC).

The next ABC to be held is ABC N (the N-th ABC ever held).
Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.

What is the earliest ABC where Kurohashi can make his debut?

Constraints

100 \leq N \leq 999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If the earliest ABC where Kurohashi can make his debut is ABC n, print n.

Sample Input 1

111

Sample Output 1

111

The next ABC to be held is ABC 111, where Kurohashi can make his debut.

Sample Input 2

112

Sample Output 2

222

The next ABC to be held is ABC 112, which means Kurohashi can no longer participate in ABC 111.
Among the ABCs where Kurohashi can make his debut, the earliest one is ABC 222.

Sample Input 3

750

Sample Output 3

777


(defparameter *s* (coerce (read-line) 'list))
(defparameter *t* (coerce (read-line) 'list))

(defparameter *alphabet* (coerce "abcdefghijklmnopqrstuvwxyz" 'list))

(defun f (str)
  (mapcar (lambda (x) (count x str)) *alphabet*))

(defun g (str1 str2)
  (if (equal (sort (remove 0 (f str1)) #'<)
             (sort (remove 0 (f str2)) #'<))
      "Yes"
      "No"))

(princ (g *s* *t*))

Score : 300 points

Problem Statement

You are given strings S and T consisting of lowercase English letters.

You can perform the following operation on S any number of times:

Operation: Choose two distinct lowercase English letters c_1 and c_2, then replace every occurrence of c_1 with c_2, and every occurrence of c_2 with c_1.

Determine if S and T can be made equal by performing the operation zero or more times.

Constraints

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

|S| = |T|

S and T consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S and T can be made equal, print Yes; otherwise, print No.

Sample Input 1

azzel
apple

Sample Output 1

Yes

azzel can be changed to apple, as follows:

Choose e as c_1 and l as c_2. azzel becomes azzle.

Choose z as c_1 and p as c_2. azzle becomes apple.

Sample Input 2

chokudai
redcoder

Sample Output 2

No

No sequences of operation can change chokudai to redcoder.

Sample Input 3

abcdefghijklmnopqrstuvwxyz
ibyhqfrekavclxjstdwgpzmonu

Sample Output 3

Yes


;; -*- coding: utf-8 -*-
#-(or child-sbcl swank)
(quit
 :unix-status
 (process-exit-code
  (run-program *runtime-pathname*
               '("--control-stack-size" "32MB"
                 "--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)
  (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 nlet (name args &body body)
  (labels ((ensure-list (x) (if (listp x) x (list x))))
    (let ((args (mapcar #'ensure-list args)))
      `(labels ((,name ,(mapcar #'car args) ,@body))
         (,name ,@(mapcar #'cadr args))))))

(declaim (ftype (function * (values simple-bit-vector &optional)) make-prime-table))
(defun make-prime-table (size)
  "Erzeugt die Primzahlentabelle 0 zu SIZE-1."
  (declare (optimize (speed 3) (safety 1)))
  (let ((dict (make-array size :element-type 'bit :initial-element 1)))
    (setf (sbit dict 0) 0 (sbit dict 1) 0)
    (loop for even-num from 4 below size by 2
          do (setf (sbit dict even-num) 0))
    (loop for p from 3 to (ceiling (sqrt size)) by 2
          when (= 1 (sbit dict p))
          do (loop for composite from (+ p p) below size by p
                   until (>= composite size)
                   do (setf (sbit dict composite) 0)))
    dict))

;; (with-memoizing (:hash-table :test #'equal :key #'cons)
;;   (defun ...))
;; (with-memoizing (:array '(10 10 10) :initial-element -1 :element-type 'fixnum)
;;   (defun ...))
(defmacro with-memoizing (cache-attribs def-form)
  (let* ((cache-attribs (if (atom cache-attribs) (list cache-attribs) cache-attribs))
         (cache-type (first cache-attribs))
         (dimensions (when (eql cache-type :array) (second cache-attribs)))
         (rank (length dimensions))
         (rest-attribs (ecase cache-type
                         (:hash-table (cdr cache-attribs))
                         (:array (cddr cache-attribs))))
         (key (prog1 (getf rest-attribs :key) (remf rest-attribs :key)))
         (cache-form (case cache-type
                       (:hash-table `(make-hash-table ,@rest-attribs))
                       (:array `(make-array ,dimensions ,@rest-attribs))))
         (initial-element (when (eql cache-type :array)
                            (assert (member :initial-element rest-attribs))
                            (getf rest-attribs :initial-element))))
    (let ((cache (gensym))
          (value (gensym))
	  (present-p (gensym))
          (name-alias (gensym))
	  (args-lst (gensym))
          (indices (loop repeat rank collect (gensym))))
      (labels ((make-cache-check-form (cache-type args)
                 (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
                    (if key
                        `(multiple-value-bind ,indices
                             (funcall ,key ,@args)
                           (let ((,value (aref ,cache ,@indices)))
                             (if (eql ,initial-element ,value)
                                 (setf (aref ,cache ,@indices)
                                       (,name-alias ,@args))
                                 ,value)))
                        `(let ((,value (aref ,cache ,@args)))
                           (if (eql ,initial-element ,value)
                               (setf (aref ,cache ,@args)
                                     (,name-alias ,@args))
                               ,value))))))
               (make-reset-form (cache-type)
                 (case cache-type
                   (:hash-table `(setf ,cache (make-hash-table ,@rest-attribs)))
                   (:array `(prog1 nil
                              (fill (array-storage-vector ,cache) ,initial-element)))))
               (make-reset-name (name)
                 (intern (format nil "RESET-~A" (symbol-name name)))))
        (ecase (car def-form)
          ((defun)
           (destructuring-bind (_ name args &body body) def-form
             (declare (ignore _))
             `(let ((,cache ,cache-form))
                (defun ,(make-reset-name name) () ,(make-reset-form cache-type))
                (defun ,name ,args
                  (labels ((,name-alias ,args ,@body))
                    (declare (inline ,name-alias))
                    ,(make-cache-check-form cache-type args))))))
          ((nlet)
           (destructuring-bind (_ name bindings &body body) def-form
             (declare (ignore _))
             `(let ((,cache ,cache-form))
                (nlet ,name ,bindings
                  ,(let ((args (mapcar (lambda (x) (if (atom x) x (car x))) bindings)))
                     `(labels ((,name-alias ,args ,@body))
                        (declare (inline ,name-alias))
                        ,(make-cache-check-form cache-type args)))))))
          ((labels flet)
           (destructuring-bind (_ definitions &body labels-body) def-form
             (declare (ignore _))
             (destructuring-bind (name args &body body) (car definitions)
               `(let ((,cache ,cache-form))
                  (,(car def-form)
                   ((,(make-reset-name name) () ,(make-reset-form cache-type))
                    (,name ,args
                           (labels ((,name-alias ,args ,@body))
                             (declare (inline ,name-alias))
                             ,(make-cache-check-form cache-type args)))
                    ,@(cdr definitions))
                   (declare (ignorable #',(make-reset-name name)))
                   ,@labels-body))))))))))

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

;; Hauptteil
(defconstant +magic+ #.(+ 7 (expt 10 9)))
(defun decompose (m)
  (declare #.OPT
           (uint32 m))
  (let* ((factor-sup (ceiling (sqrt m)))
         (prime-table (make-prime-table (1+ factor-sup))))
    (loop for i from 2 below (length prime-table)
          when (= 1 (sbit prime-table i))
          collect (nlet recurse ((count 0))
                    (declare (uint32 count))
                    (multiple-value-bind (quot rem) (floor m i)
                      (if (zerop rem)
                          (progn (setf m quot)
                                 (recurse (1+ count)))
                          count)))
          into factors
          finally (return
                    (let ((factors (delete 0 (the list factors))))
                      (if (= 1 m)
                          factors
                          (append factors (list 1))))))))

(with-memoizing (:array '(100001 32) :element-type 'fixnum :initial-element -1)
  (defun multiset-coefficient (n k)
    (declare #.OPT
             ((integer 1 #.most-positive-fixnum) n)
             ((integer 0 #.most-positive-fixnum) k))
    (cond ((zerop k) 1)
          ((= n 1) 1)
          (t (mod (the uint63 (+ (multiset-coefficient (- n 1) k)
                                 (multiset-coefficient n (- k 1))))
                  +magic+)))))

(defun main ()
  (let* ((n (read))
         (m (read))
         (factors (decompose m)))
    (if (= m 1)
        (println 1)
        (println
         (reduce (lambda (x y) (mod (* x y) +magic+))
                 factors
                 :key (lambda (k) (multiset-coefficient n k)))))))

#-swank(main)

Score : 400 points

Problem Statement

You are given positive integers N and M.

How many sequences a of length N consisting of positive integers satisfy a_1 \times a_2 \times ... \times a_N = M? Find the count modulo 10^9+7.

Here, two sequences a' and a'' are considered different when there exists some i such that a_i' \neq a_i''.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^9

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of the sequences consisting of positive integers that satisfy the condition, modulo 10^9 + 7.

Sample Input 1

2 6

Sample Output 1

4

Four sequences satisfy the condition: \{a_1, a_2\} = \{1, 6\}, \{2, 3\}, \{3, 2\} and \{6, 1\}.

Sample Input 2

3 12

Sample Output 2

18

Sample Input 3

100000 1000000000

Sample Output 3

957870001


;; -*- coding: utf-8 -*-
#-(or child-sbcl swank)
(quit
 :unix-status
 (process-exit-code
  (run-program *runtime-pathname*
               '("--control-stack-size" "32MB"
                 "--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)
  (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 nlet (name args &body body)
  (labels ((ensure-list (x) (if (listp x) x (list x))))
    (let ((args (mapcar #'ensure-list args)))
      `(labels ((,name ,(mapcar #'car args) ,@body))
         (,name ,@(mapcar #'cadr args))))))

(declaim (ftype (function * (values simple-bit-vector &optional)) make-prime-table))
(defun make-prime-table (size)
  "Erzeugt die Primzahlentabelle 0 zu SIZE-1."
  (declare (optimize (speed 3) (safety 1)))
  (let ((dict (make-array size :element-type 'bit :initial-element 1)))
    (setf (sbit dict 0) 0 (sbit dict 1) 0)
    (loop for even-num from 4 below size by 2
          do (setf (sbit dict even-num) 0))
    (loop for p from 3 to (ceiling (sqrt size)) by 2
          when (= 1 (sbit dict p))
          do (loop for composite from (+ p p) below size by p
                   until (>= composite size)
                   do (setf (sbit dict composite) 0)))
    dict))

;; (with-memoizing (:hash-table :test #'equal :key #'cons)
;;   (defun ...))
;; (with-memoizing (:array '(10 10 10) :initial-element -1 :element-type 'fixnum)
;;   (defun ...))
(defmacro with-memoizing (cache-attribs def-form)
  (let* ((cache-attribs (if (atom cache-attribs) (list cache-attribs) cache-attribs))
         (cache-type (first cache-attribs))
         (dimensions (when (eql cache-type :array) (second cache-attribs)))
         (rank (length dimensions))
         (rest-attribs (ecase cache-type
                         (:hash-table (cdr cache-attribs))
                         (:array (cddr cache-attribs))))
         (key (prog1 (getf rest-attribs :key) (remf rest-attribs :key)))
         (cache-form (case cache-type
                       (:hash-table `(make-hash-table ,@rest-attribs))
                       (:array `(make-array ,dimensions ,@rest-attribs))))
         (initial-element (when (eql cache-type :array)
                            (assert (member :initial-element rest-attribs))
                            (getf rest-attribs :initial-element))))
    (let ((cache (gensym))
          (value (gensym))
	  (present-p (gensym))
          (name-alias (gensym))
	  (args-lst (gensym))
          (indices (loop repeat rank collect (gensym))))
      (labels ((make-cache-check-form (cache-type args)
                 (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
                    (if key
                        `(multiple-value-bind ,indices
                             (funcall ,key ,@args)
                           (let ((,value (aref ,cache ,@indices)))
                             (if (eql ,initial-element ,value)
                                 (setf (aref ,cache ,@indices)
                                       (,name-alias ,@args))
                                 ,value)))
                        `(let ((,value (aref ,cache ,@args)))
                           (if (eql ,initial-element ,value)
                               (setf (aref ,cache ,@args)
                                     (,name-alias ,@args))
                               ,value))))))
               (make-reset-form (cache-type)
                 (case cache-type
                   (:hash-table `(setf ,cache (make-hash-table ,@rest-attribs)))
                   (:array `(prog1 nil
                              (fill (array-storage-vector ,cache) ,initial-element)))))
               (make-reset-name (name)
                 (intern (format nil "RESET-~A" (symbol-name name)))))
        (ecase (car def-form)
          ((defun)
           (destructuring-bind (_ name args &body body) def-form
             (declare (ignore _))
             `(let ((,cache ,cache-form))
                (defun ,(make-reset-name name) () ,(make-reset-form cache-type))
                (defun ,name ,args
                  (labels ((,name-alias ,args ,@body))
                    (declare (inline ,name-alias))
                    ,(make-cache-check-form cache-type args))))))
          ((nlet)
           (destructuring-bind (_ name bindings &body body) def-form
             (declare (ignore _))
             `(let ((,cache ,cache-form))
                (nlet ,name ,bindings
                  ,(let ((args (mapcar (lambda (x) (if (atom x) x (car x))) bindings)))
                     `(labels ((,name-alias ,args ,@body))
                        (declare (inline ,name-alias))
                        ,(make-cache-check-form cache-type args)))))))
          ((labels flet)
           (destructuring-bind (_ definitions &body labels-body) def-form
             (declare (ignore _))
             (destructuring-bind (name args &body body) (car definitions)
               `(let ((,cache ,cache-form))
                  (,(car def-form)
                   ((,(make-reset-name name) () ,(make-reset-form cache-type))
                    (,name ,args
                           (labels ((,name-alias ,args ,@body))
                             (declare (inline ,name-alias))
                             ,(make-cache-check-form cache-type args)))
                    ,@(cdr definitions))
                   (declare (ignorable #',(make-reset-name name)))
                   ,@labels-body))))))))))

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

;; Hauptteil
(defconstant +magic+ #.(+ 7 (expt 10 9)))
(defun decompose (m prime-table)
  (declare #.OPT
           (simple-bit-vector prime-table)
           (uint32 m))
  (loop for i from 2 below (length prime-table)
        when (= 1 (sbit prime-table i))
        collect (nlet recurse ((count 0))
                  (declare (uint32 count))
                  (multiple-value-bind (quot rem) (floor m i)
                    (if (zerop rem)
                        (progn (setf m quot)
                               (recurse (1+ count)))
                        count)))
        into factors
        finally (let ((factors (delete 0 (the list factors))))
                  (return (or factors (list 1))))))

(with-memoizing (:array '(100001 32) :element-type 'fixnum :initial-element -1)
  (defun multiset-coefficient (n k)
    (declare #.OPT
             ((integer 1 #.most-positive-fixnum) n)
             ((integer 0 #.most-positive-fixnum) k))
    (cond ((zerop k) 1)
          ((= n 1) 1)
          (t (mod (the uint63 (+ (multiset-coefficient (- n 1) k)
                                 (multiset-coefficient n (- k 1))))
                  +magic+)))))

(defun main ()
  (let* ((n (read))
         (m (read))
         (max-prime (ceiling (sqrt m)))
         (prime-table (make-prime-table (1+ max-prime)))
         (factors (decompose m prime-table)))
    (println
     (reduce (lambda (x y) (mod (* x y) +magic+))
             factors
             :key (lambda (k) (multiset-coefficient n k))))))

#-swank(main)


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

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

(defmacro collect-times (time body)
  `(loop repeat ,time collect ,body))

(defun read-times (time)
  (collect-times time (read)))

(defmacro aif (expr then else)
  `(let ((it ,expr))
     (if it ,then ,else)))

(defmacro awhen (expr &rest then)
  `(aif ,expr (progn ,@then) nil))

(defun comulative (function list &key base)
  (if base
      (comulative function (cons base list))
      (do ((lst (cdr list) (cdr lst))
           (acc (list (car list))))
          ((null lst) (reverse acc))
        (push (funcall function (car acc) (car lst)) acc))))

(defun binary-search (function left right
                      &optional
                        (eps 1)
                        (average-function (lambda (x y) (ash (+ x y) -1))))
  (if (<= (abs (- left right)) eps)
      right
      (let ((mid (funcall average-function left right)))
        (if (funcall function mid)
            (binary-search function left mid eps average-function)
            (binary-search function mid right eps average-function)))))

(defun arithmetic-mean (&rest body)
  (/ (apply #'+ body) (length body)))

(defvar +MOD+ (+ (expt 10 9) 7))

(defun main (n sum kids)
  (let ((sums (coerce (comulative #'+ (sort kids #'<)) 'vector)))
    (- (binary-search (lambda (x) (> (aref sums x) sum)) -1 n)
       (if (< (apply #'+ kids) sum) 1 0))))

(let ((n (read))
      (x (read)))
  (princ (main n x (read-times n))))

Score : 200 points

Problem Statement

There are N children, numbered 1, 2, ..., N.

Snuke has decided to distribute x sweets among them.
He needs to give out all the x sweets, but some of the children may get zero sweets.

For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets.
Snuke is trying to maximize the number of happy children by optimally distributing the sweets.
Find the maximum possible number of happy children.

Constraints

All values in input are integers.

2 \leq N \leq 100

1 \leq x \leq 10^9

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N x
a_1 a_2 ... a_N

Output

Print the maximum possible number of happy children.

Sample Input 1

3 70
20 30 10

Sample Output 1

2

One optimal way to distribute sweets is (20, 30, 20).

Sample Input 2

3 10
20 30 10

Sample Output 2

1

The optimal way to distribute sweets is (0, 0, 10).

Sample Input 3

4 1111
1 10 100 1000

Sample Output 3

4

The optimal way to distribute sweets is (1, 10, 100, 1000).

Sample Input 4

2 10
20 20

Sample Output 4

0

No children will be happy, no matter how the sweets are distributed.


(let* ((n (read))
       (m (read))
       (lst (sort (loop :repeat n :collect (read)) #'<))
       (ans 0))
  (setf ans (count t (mapcar (lambda (k) (setf m (- m k)) (<= 0 m)) lst)))
  (if (= m 0)
      (princ ans)
      (princ (1- ans))))


(defparameter n (read))
(defparameter x (read))
(defparameter a (loop repeat n
                      collect (read)))

(defun f (x a c)
  (let ((head (car a))
        (tail (cdr a)))
    (if (< x head)
        c
        (f (- x head) tail (1+ c)))))

(defun g (x a c)
  (if (null a)
      (1- c)
      (g (- x (car a)) (cdr a) (1+ c))))

(princ
  (if (< x (apply #'+ a))
      (f x (sort a #'<) 0)
      (g x (sort a #'>) 0)))


(defparameter n (read))
(defparameter x (read))
(defparameter a (loop repeat n
                      collect (read)))
(defun f (x a c)
  (cond ((null a) (1- c))
        ((< x (car a)) c)
        (t (f (- x (car a)) (cdr a) (1+ c)))))
(f x (sort a #'<) 0)


(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
(declaim (inline split-ints-into-vector))
(defun split-ints-into-vector (string dest-vector &key (offset 0))
  (declare (string string)
           ((simple-array * (*)) dest-vector)
           ((integer 0 #.most-positive-fixnum) offset))
  (loop for idx from offset below (length dest-vector)
        for pos1 = 0 then (1+ pos2)
        for pos2 = (position #\space string :start pos1 :test #'char=)
        do (setf (aref dest-vector idx)
                 (parse-integer string :start pos1 :end pos2))
        finally (return dest-vector)))

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

;; Hauptteil

(defmacro with-collecting (&body body)
  (let ((list (gensym))
        (head (gensym))
        (length (gensym)))
    `(let* ((,list (list :dummy-element))
            (,head ,list)
            (,length 0))
       (labels ((collect (x)
                  (setf (cdr ,list) (list x))
                  (setf ,list (cdr ,list))
                  (incf ,length)))
         ,@body
         (values (cdr ,head) ,length)))))

(defun main ()
  (let* ((h (read))
         (w (read))
         (matrix (make-array (list h w) :element-type 'uint4))
         (row (make-array w :element-type 'uint4)))
    (dotimes (i h)
      (split-ints-into-vector (read-line) row)
      (dotimes (j w)
        (setf (aref matrix i j) (aref row j))))
    (multiple-value-bind (operations n)
        (with-collecting
          (dotimes (i h)
            (cond ((zerop i)
                   (loop for j from 0 below (- w 1)
                         when (oddp (aref matrix i j))
                         do (decf (aref matrix i j))
                            (incf (aref matrix i (+ j 1)))
                            (collect (list i j i (+ j 1)))))
                  ((oddp i)
                   (when (oddp (aref matrix (- i 1) (- w 1)))
                     (decf (aref matrix (- i 1) (- w 1)))
                     (incf (aref matrix i (- w 1)))
                     (collect (list (- i 1) (- w 1) i (- w 1))))
                   (loop for j from (- w 1) above 0
                         when (oddp (aref matrix i j))
                         do (decf (aref matrix i j))
                            (incf (aref matrix i (- j 1)))
                            (collect (list i j i (- j 1)))))
                  ((evenp i)
                   (when (oddp (aref matrix (- i 1) 0))
                     (decf (aref matrix (- i 1) 0))
                     (incf (aref matrix i 0))
                     (collect (list (- i 1) 0 i 0)))
                   (loop for j from 0 below (- w 1)
                         when (oddp (aref matrix i j))
                         do (decf (aref matrix i j))
                            (incf (aref matrix i (+ j 1)))
                            (collect (list i j i (+ j 1))))))))
      (println n)
      (dolist (op operations)
        (destructuring-bind (i1 j1 i2 j2) op
          (format t "~A ~A ~A ~A~%" (+ i1 1) (+ j1 1) (+ i2 1) (+ j2 1)))))))

#-swank(main)

Score : 400 points

Problem Statement

There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).

In Cell (i, j), a_{ij} coins are placed.

You can perform the following operation any number of times:

Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.

Maximize the number of cells containing an even number of coins.

Constraints

All values in input are integers.

1 \leq H, W \leq 500

0 \leq a_{ij} \leq 9

Input

Input is given from Standard Input in the following format:

H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}

Output

Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:

N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'

That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.

In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').

Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.

Sample Input 1

2 3
1 2 3
0 1 1

Sample Output 1

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

Every cell contains an even number of coins after the following sequence of operations:

Move the coin in Cell (2, 2) to Cell (2, 3).

Move the coin in Cell (1, 1) to Cell (1, 2).

Move one of the coins in Cell (1, 3) to Cell (1, 2).

Sample Input 2

3 2
1 0
2 1
1 0

Sample Output 2

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

Sample Input 3

1 5
9 9 9 9 9

Sample Output 3

2
1 1 1 2
1 3 1 4


(defun calcOdd (n)
   (* (/ (- n 1) 2) (+ 1 (/ (- n 1) 2)))
  )
(defun pair (n)
  (if (evenp n)
      (expt (/ n 2) 2)
      (calcOdd n)
      )
  )
(princ (pair (read)))

Score : 100 points

Problem Statement

Find the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive). The order does not matter.

Constraints

2\leq K\leq 100

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive).

Sample Input 1

3

Sample Output 1

2

Two pairs can be chosen: (2,1) and (2,3).

Sample Input 2

6

Sample Output 2

9

Sample Input 3

11

Sample Output 3

30

Sample Input 4

50

Sample Output 4

625


(defparameter k (read))
(defvar q)
(defvar res)

(multiple-value-bind (q res) (floor k 2)
  (if (= res 0)
    (princ (expt q 2))
    (princ (* q (incf q)))))


(defun a (x)
  (if (= 1 (mod x 2))
      (floor (* (1- x) (1+ x)) 4)
      (floor (* x x) 4)))

(a (parse-integer (read)))


(defvar *ans*)

(defun solve (x1 y1 x2 y2)
  (let (x3 y3 x4 y4)
    (setq x3 (- x2 (- y2 y1)))
    (setq y3 (+ y2 (- x2 x1)))
    (setq x4 (- x1 (- y2 y1)))
    (setq y4 (+ y1 (- x2 x1)))
    (list x3 y3 x4 y4)))

(defun main ()
  (let ((x1 (read))
        (y1 (read))
        (x2 (read))
        (y2 (read)))
    (setf *ans* (solve x1 y1 x2 y2))
    (fresh-line)
    (dotimes (i 4)
      (princ (nth i *ans*))
      (princ #\space))
    (princ #\newline)
    (fresh-line)))

(main)

Score : 200 points

Problem Statement

There is a square in the xy-plane. The coordinates of its four vertices are (x_1,y_1),(x_2,y_2),(x_3,y_3) and (x_4,y_4) in counter-clockwise order.
(Assume that the positive x-axis points right, and the positive y-axis points up.)

Takahashi remembers (x_1,y_1) and (x_2,y_2), but he has forgot (x_3,y_3) and (x_4,y_4).

Given x_1,x_2,y_1,y_2, restore x_3,y_3,x_4,y_4. It can be shown that x_3,y_3,x_4 and y_4 uniquely exist and have integer values.

Constraints

|x_1|,|y_1|,|x_2|,|y_2| \leq 100

(x_1,y_1) ≠ (x_2,y_2)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

x_1 y_1 x_2 y_2

Output

Print x_3,y_3,x_4 and y_4 as integers, in this order.

Sample Input 1

0 0 0 1

Sample Output 1

-1 1 -1 0

(0,0),(0,1),(-1,1),(-1,0) is the four vertices of a square in counter-clockwise order.
Note that (x_3,y_3)=(1,1),(x_4,y_4)=(1,0) is not accepted, as the vertices are in clockwise order.

Sample Input 2

2 3 6 6

Sample Output 2

3 10 -1 7

Sample Input 3

31 -41 -59 26

Sample Output 3

-126 -64 -36 -131


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

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

(defmacro collect-times (time body)
  `(loop repeat ,time collect ,body))

(defun read-times (time)
  (collect-times time (read)))

(defmacro aif (expr then else)
    `(let ((it ,expr))
       ,then
       ,else))

(defun read2 ()
  (cons (read) (read)))

(defun add (a b)
  (cons (+ (car a) (car b)) (+ (cdr a) (cdr b))))

(defun sub (a b)
  (cons (- (car a) (car b)) (- (cdr a) (cdr b))))

(defun rot (x)
  (cons (- 0 (cdr x)) (car x)))

(defun tolist (x)
  (list (car x) (cdr x)))

(defun main (v1 v2)
  (let ((adder (rot (sub v2 v1))))
    (append (tolist (add v2 adder)) (tolist (add v1 adder)))))

(format t "~{~a~^ ~}" (main (read2) (read2)))

(main (read2) (read2))


(defun b (x1 y1 x2 y2)
  (let ((x3 x2)
	(x4 x1)
	(y3 (+ y2 (- x2 x1)))
	(y4 (+ y1 (- x2 x1))))
    (list x3 y3 x3 x4)))

(defun split (line)
  (let ((result ()) (str ""))
    (dolist (i (loop for i across line collect i))
      (if (eql i #\space)
	  (progn
	    (setf result (append result (list (parse-integer str))))
	    (setf str ""))
	  (setf str (concatenate 'string str (string i)))))
    (setf result (append result (list (parse-integer str))))
    result))

(format t "~{~a ~}" (eval `(b ,@(split (read-line)))))


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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (let* ((n (read))
         (k (read)))
    (println
     (if (oddp k)
         (expt (floor n k) 3)
         (+ (expt (floor (+ n (floor k 2)) k) 3)
            (expt (floor n k) 3))))))

#-swank(main)

Score : 300 points

Problem Statement

You are given integers N and K. Find the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K.
The order of a,b,c does matter, and some of them can be the same.

Constraints

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

N and K are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K.

Sample Input 1

3 2

Sample Output 1

9

(1,1,1),(1,1,3),(1,3,1),(1,3,3),(2,2,2),(3,1,1),(3,1,3),(3,3,1) and (3,3,3) satisfy the condition.

Sample Input 2

5 3

Sample Output 2

1

Sample Input 3

31415 9265

Sample Output 3

27

Sample Input 4

35897 932

Sample Output 4

114191


(defun a (n i)
  (- (+ n 1) i)
  )
(princ (a (read)))

Score : 100 points

Problem Statement

There is an N-car train.

You are given an integer i. Find the value of j such that the following statement is true: "the i-th car from the front of the train is the j-th car from the back."

Constraints

1 \leq N \leq 100

1 \leq i \leq N

Input

Input is given from Standard Input in the following format:

N i

Output

Print the answer.

Sample Input 1

4 2

Sample Output 1

3

The second car from the front of a 4-car train is the third car from the back.

Sample Input 2

1 1

Sample Output 2

1

Sample Input 3

15 11

Sample Output 3

5


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

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

;;macros
(defmacro println (n)
  `(format t "~a~%" ,n))
(defmacro vint-out (vec)
  `(progn
     (rep i (length ,vec)
          (princ (vref ,vec i))
          (princ " "))
     (fresh-line)))

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

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

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

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

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

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

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

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

(defmacro defchangef (name op default-val)
  `(defmacro ,name (var &optional (val ,default-val))
     `(setq ,var (,',op ,val ,var))))

;;本体
(defun main()
  (let ((n (read))(i (read)))
    (println (- (1+ n) i))))

#-swank(main)


;;; body

(defun solve (n k x)
  (flet ((calc-dist (i-left i-right)
           (min (+ (abs i-left) (abs (- i-right i-left)))
                (+ (abs i-right) (abs (- i-right i-left))))))
    (if (= n 1)
        (abs (aref x 0))
        (reduce #'min
                (loop for i below (1+ (- n k)) collect
                     (calc-dist (aref x i)
                                (aref x (1- (+ i k)))))))))

(defun main ()
  (let ((n (read))
        (k (read)))
    (let ((x (make-array n
                         :initial-contents (loop repeat n collect (read)))))
      (princ (solve n k x))
      (fresh-line))))

#-swank (main)

Score : 300 points

Problem Statement

There are N candles placed on a number line.
The i-th candle from the left is placed on coordinate x_i.
Here, x_1 < x_2 < ... < x_N holds.

Initially, no candles are burning.
Snuke decides to light K of the N candles.

Now, he is at coordinate 0.
He can move left and right along the line with speed 1.
He can also light a candle when he is at the same position as the candle, in negligible time.

Find the minimum time required to light K candles.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq N

x_i is an integer.

|x_i| \leq 10^8

x_1 < x_2 < ... < x_N

Input

Input is given from Standard Input in the following format:

N K
x_1 x_2 ... x_N

Output

Print the minimum time required to light K candles.

Sample Input 1

5 3
-30 -10 10 20 50

Sample Output 1

40

He should move and light candles as follows:

Move from coordinate 0 to -10.

Light the second candle from the left.

Move from coordinate -10 to 10.

Light the third candle from the left.

Move from coordinate 10 to 20.

Light the fourth candle from the left.

Sample Input 2

3 2
10 20 30

Sample Output 2

20

Sample Input 3

1 1
0

Sample Output 3

0

There may be a candle placed at coordinate 0.

Sample Input 4

8 5
-9 -7 -4 -3 1 2 3 4

Sample Output 4

10


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

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

;;;
;;; Calculate inversion number by merge sort
;;;

(declaim (inline %merge-count))
(defun %merge-count (l mid r source-vec dest-vec predicate)
  (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
                        (aref source-vec j)
                        (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)))

(declaim (inline calc-inversion-number!))
(defun calc-inversion-number! (vector predicate &key (start 0) end)
  "Calculates the inversion number 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 (length vector) :element-type (array-element-type vector))))
      (labels
          ((recurse (l r merge-to-vec1-p)
             (declare (optimize (safety 0))
                      ((integer 0 #.array-total-size-limit) l r))
             (cond ;; 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+
                          (+ (recurse l mid (not merge-to-vec1-p))
                             (recurse mid r (not merge-to-vec1-p))
                             (if merge-to-vec1-p
                                 (%merge-count l mid r buffer vector predicate)
                                 (%merge-count l mid r vector buffer predicate)))))))))
        (recurse start end t)))))

;; Scheme-style named let
(defmacro nlet (name args &body body)
  (labels ((ensure-list (x) (if (listp x) x (list x))))
    (let ((args (mapcar #'ensure-list args)))
      `(labels ((,name ,(mapcar #'car args) ,@body))
         (,name ,@(mapcar #'cadr args))))))

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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun feasible-p (as x)
  (declare #.OPT
           ((simple-array uint32 (*)) as)
           (uint32 x))
  (let* ((n (length as))
         (cumul (make-array (+ n 1) :element-type 'int32 :initial-element 0)))
    (dotimes (i n)
      (setf (aref cumul (+ i 1))
            (+ (aref cumul i) (if (>= (aref as i) x) 1 -1))))
    (let ((non-inversion-number (- (ash (* n (+ n 1)) -1)
                                   (calc-inversion-number! cumul #'<)))
          (threshold (ceiling (* n (+ n 1)) 4)))
      (>= non-inversion-number threshold))))

(defun main ()
  (let* ((n (read))
         (as (make-array n :element-type 'uint32)))
    (dotimes (i n) (setf (aref as i) (read-fixnum)))
    (nlet bisect ((ok 1) (ng 1000000001))
      (if (<= (- ng ok) 1)
          (println ok)
          (let ((mid (ash (+ ok ng) -1)))
            (if (feasible-p as mid)
                (bisect mid ng)
                (bisect ok mid)))))))

#-swank(main)

Score : 700 points

Problem Statement

We will define the median of a sequence b of length M, as follows:

Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.

For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.

Snuke comes up with the following problem.

You are given a sequence a of length N.
For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a.
We will list m_{l, r} for all pairs (l, r) to create a new sequence m.
Find the median of m.

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 median of m.

Sample Input 1

3
10 30 20

Sample Output 1

30

The median of each contiguous subsequence of a is as follows:

The median of (10) is 10.

The median of (30) is 30.

The median of (20) is 20.

The median of (10, 30) is 30.

The median of (30, 20) is 30.

The median of (10, 30, 20) is 20.

Thus, m = (10, 30, 20, 30, 30, 20) and the median of m is 30.

Sample Input 2

1
10

Sample Output 2

10

Sample Input 3

10
5 9 5 9 8 9 3 5 4 3

Sample Output 3

8


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

;; BEGIN_INSERTED_CONTENTS
;;;
;;; 1-dimensional binary indexed tree
;;;

;; TODO: multidimensional BIT

(defmacro define-bitree (name &key (operator '#'+) (identity 0) sum-type (order '#'>))
  "OPERATOR := binary operator (on a commutative monoid)
IDENTITY := object (identity element of the monoid)
ORDER := nil | strict comparison operator on the monoid
SUM-TYPE := nil | type specifier

Defines no structure; BIT is just a vector. This macro defines the three
function: <NAME>-UPDATE!, <NAME>-SUM and COERCE-TO-<NAME>!. If ORDER is
specified, this macro defines the bisection function <NAME>-BISECT-LEFT in
addition. (Note that the -BISECT-LEFT function works only when the sequence of
prefix sums (VECTOR[0], VECTOR[0]+VECTOR[1], ...) is monotonous.)

SUM-TYPE is used only for the type declaration: each sum
VECTOR[i]+VECTOR[i+1]...+VECTOR[i+k] is declared to be this type. (The
element-type of vector itself doesn't need to be SUM-TYPE.)"
  (let* ((name (string name))
         (fname-update (intern (format nil "~A-UPDATE!" name)))
         (fname-sum (intern (format nil "~A-SUM" name)))
         (fname-coerce (intern (format nil "COERCE-TO-~A!" name)))
         (fname-bisect-left (intern (format nil "~A-BISECT-LEFT" name)))
         (fname-bisect-right (intern (format nil "~A-BISECT-RIGHT" name))))
    `(progn
       (declaim (inline ,fname-update))
       (defun ,fname-update (bitree index delta)
         "Destructively increments the vector: vector[INDEX] = vector[INDEX] +
DELTA"
         (let ((len (length bitree)))
           (do ((i index (logior i (+ i 1))))
               ((>= i len) bitree)
             (declare ((integer 0 #.most-positive-fixnum) i))
             (setf (aref bitree i)
                   (funcall ,operator (aref bitree i) delta)))))

       (declaim (inline ,fname-sum))
       (defun ,fname-sum (bitree end)
         "Returns the sum of the prefix: vector[0] + ... + vector[END-1]."
         (declare ((integer 0 #.most-positive-fixnum) end))
         (let ((res ,identity))
           ,@(when sum-type `((declare (type ,sum-type res))))
           (do ((i (- end 1) (- (logand i (+ i 1)) 1)))
               ((< i 0) res)
             (declare ((integer -1 #.most-positive-fixnum) i))
             (setf res (funcall ,operator res (aref bitree i))))))

       (declaim (inline ,fname-coerce))
       (defun ,fname-coerce (vector)
         "Destructively constructs BIT from VECTOR."
         (loop with len = (length vector)
               for i below len
               for dest-i = (logior i (+ i 1))
               when (< dest-i len)
               do (setf (aref vector dest-i)
                        (funcall ,operator (aref vector dest-i) (aref vector i)))
               finally (return vector)))

       ,@(when order
           `((declaim (inline ,fname-bisect-left))
             (defun ,fname-bisect-left (bitree value)
               "Returns the smallest index that fulfills VECTOR[0]+ ... +
VECTOR[index] >= VALUE. Returns the length of VECTOR if VECTOR[0]+
... +VECTOR[length-1] < VALUE."
               (declare (vector bitree))
               (if (not (funcall ,order value ,identity))
                   0
                   (let ((len (length bitree))
                         (index+1 0)
                         (cumul ,identity))
                     (declare ((integer 0 #.most-positive-fixnum) index+1)
                              ,@(when sum-type
                                  `((type ,sum-type cumul))))
                     (do ((delta (ash 1 (- (integer-length len) 1))
                                 (ash delta -1)))
                         ((zerop delta) index+1)
                       (declare ((integer 0 #.most-positive-fixnum) delta))
                       (let ((next-index (+ index+1 delta -1)))
                         (when (< next-index len)
                           (let ((next-cumul (funcall ,operator cumul (aref bitree next-index))))
                             ,@(when sum-type
                                 `((declare (type ,sum-type next-cumul))))
                             (when (funcall ,order value next-cumul)
                               (setf cumul next-cumul)
                               (incf index+1 delta)))))))))
             (declaim (inline ,fname-bisect-right))
             (defun ,fname-bisect-right (bitree value)
               "Returns the smallest index that fulfills VECTOR[0]+ ... +
VECTOR[index] > VALUE. Returns the length of VECTOR if VECTOR[0]+
... +VECTOR[length-1] <= VALUE."
               (declare (vector bitree))
               (if (funcall ,order ,identity value)
                   0
                   (let ((len (length bitree))
                         (index+1 0)
                         (cumul ,identity))
                     (declare ((integer 0 #.most-positive-fixnum) index+1)
                              ,@(when sum-type
                                  `((type ,sum-type cumul))))
                     (do ((delta (ash 1 (- (integer-length len) 1))
                                 (ash delta -1)))
                         ((zerop delta) index+1)
                       (declare ((integer 0 #.most-positive-fixnum) delta))
                       (let ((next-index (+ index+1 delta -1)))
                         (when (< next-index len)
                           (let ((next-cumul (funcall ,operator cumul (aref bitree next-index))))
                             ,@(when sum-type
                                 `((declare (type ,sum-type next-cumul))))
                             (unless (funcall ,order next-cumul value)
                               (setf cumul next-cumul)
                               (incf index+1 delta))))))))))))))

(define-bitree bitree
  :operator #'+
  :identity 0
  :sum-type fixnum)

;; Scheme-style named let
(defmacro nlet (name args &body body)
  (labels ((ensure-list (x) (if (listp x) x (list x))))
    (let ((args (mapcar #'ensure-list args)))
      `(labels ((,name ,(mapcar #'car args) ,@body))
         (,name ,@(mapcar #'cadr args))))))

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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun feasible-p (as x)
  (declare ((simple-array uint32 (*)) as)
           (uint32 x))
  (let* ((n (length as))
         (cumul (make-array (+ n 1) :element-type 'int32 :initial-element 0))
         (dp (make-array 200001 :element-type 'uint32 :initial-element 0))
         (res 0)
         (threshold (ceiling (* n (+ n 1)) 4)))
    (declare (fixnum res threshold))
    (dotimes (i n)
      (setf (aref cumul (+ i 1))
            (+ (aref cumul i) (if (>= (aref as i) x) 1 -1))))
    (loop for r from 0 to n
          for sr = (aref cumul r)
          do (incf res (bitree-sum dp (+ 100001 sr)))
             (bitree-update! dp (+ 100000 sr) 1))
    (>= res threshold)))

(defun main ()
  (let* ((n (read))
         (as (make-array n :element-type 'uint32)))
    (dotimes (i n) (setf (aref as i) (read-fixnum)))
    (nlet bisect ((ok 1) (ng 1000000001))
      (if (<= (- ng ok) 1)
          (println ok)
          (let ((mid (ash (+ ok ng) -1)))
            (if (feasible-p as mid)
                (bisect mid ng)
                (bisect ok mid)))))))

#-swank(main)


(defvar *N* (read))

(defvar *array* (make-array *N*))
(defun set-array ()
  (dotimes (i *N*)
    (let ((x (read)))
      (setf (aref *array* i) x))))

(defun get-median (l)
  (let* ((size (length l))
         (check (round (/ (float size) 2))))
    (cond ((evenp size)
           (nth check l))
          ((= size 1)
           (nth 0 l))
          (t
           (nth (- check 1) l)))))

(defun main ()
  (set-array)
  (let ((result (reverse (coerce *array* 'list)))
         (array-size (- *N* 1)))
    (dotimes (n *N*)
      (let ((right (+ n 1)))
        (if (/= n array-size)
            (progn
              (let* ((tmp (list (aref *array* n) (aref *array* right)))
                     (sorted (sort tmp #'<)))
                (push (cadr sorted) result)))
            (push (get-median (sort (coerce *array* 'list) #'<)) result))))
    (setq result (sort (reverse result) #'<))
    (format t "~A~%" (get-median result))))

(main)


(defvar *N* (read))

(defun split-string (s d)
  (let ((l (concatenate 'list s))
        (r (list nil))
        (tmp (list nil)))
    (dolist (n l)
      (if (eql n d)
          (progn
            (push (parse-integer (concatenate 'string (cdr (reverse tmp)))) r)
            (setq tmp (list nil)))
          (push n tmp)))
    (let ((check (parse-integer (concatenate 'string (cdr (reverse tmp))) :junk-allowed t)))
      (unless (null check)
        (push check r)))
    (cdr (reverse r))))

(defun main ()
  (let ((tmp (read-line)))
    (let* ((l (split-string tmp #\Space))
           (check (round (/ (float (length l)) 2))))
      (if (= check 0)
          (format t "~a~%" (nth check l))
          (if (/= (mod check 2) 0)
              (format t "~a~%" (nth (- check 1) l))
              (progn
                (let ((x (/ (+ (nth (- check 1) l) (nth check l)) 2)))
                  (format t "~a~%" x))))))))

(main)


(in-package :cl-user)
(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 (set-dispatch-macro-character #\# #\> #'cl-debug-print:debug-print-reader)

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

(defconstant +mod+ 1000000007)

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

;; BEGIN_INSERTED_CONTENTS
(defpackage :cp/divisor
  (:use :cl)
  (:export #:enum-divisors #:enum-ascending-divisors #:make-divisors-table))
(in-package :cp/divisor)

(declaim (ftype (function * (values (vector (integer 0 #.most-positive-fixnum)) &optional))
                enum-divisors))
(defun enum-divisors (x)
  "Enumerates all the divisors of X in O(sqrt(X)) time. Note that the resultant
vector is NOT sorted."
  (declare (optimize (speed 3))
           ((integer 0 #.most-positive-fixnum) x))
  (let* ((sqrt (isqrt x))
         (result (make-array (isqrt sqrt) ; FIXME: currently set the initial size to x^1/4
                             :element-type '(integer 0 #.most-positive-fixnum)
                             :fill-pointer 0)))
    (loop for i from 1 to sqrt
          do (multiple-value-bind (quot rem) (floor x i)
               (when (zerop rem)
                 (vector-push-extend i result)
                 (unless (= i quot)
                   (vector-push-extend quot result)))))
    result))

;; Below is a variant that returns a sorted list.
(defun enum-ascending-divisors (n)
  "Returns the ascending list of all the divisors of N."
  (declare (optimize (speed 3))
           ((integer 1 #.most-positive-fixnum) n))
  (if (= n 1)
      (list 1)
      (let* ((sqrt (isqrt n))
             (result (list 1)))
        (labels ((%enum (i first-half second-half)
                   (declare ((integer 1 #.most-positive-fixnum) i))
                   (cond ((or (< i sqrt)
                              (and (= i sqrt) (/= (* sqrt sqrt) n)))
                          (multiple-value-bind (quot rem) (floor n i)
                            (if (zerop rem)
                                (progn
                                  (setf (cdr first-half) (list i))
                                  (setf second-half (cons quot second-half))
                                  (%enum (1+ i) (cdr first-half) second-half))
                                (%enum (1+ i) first-half second-half))))
                         ((= i sqrt) ; N is a square number here
                          (setf (cdr first-half) (cons i second-half)))
                         (t ; (> i sqrt)
                          (setf (cdr first-half) second-half)))))
          (%enum 2 result (list n))
          result))))

(declaim (ftype (function * (values (simple-array list (*)) &optional))
                make-divisors-table))
(defun make-divisors-table (sup)
  "Returns a vector of length SUP whose each cell, vector[X], is the ascending
list of every divisor of X. Note that vector[0] = NIL."
  (declare ((integer 0 #.most-positive-fixnum) sup)
           #+sbcl (sb-ext:muffle-conditions style-warning))
  (let ((result (make-array sup :element-type 'list))
        (tails (make-array sup :element-type 'list))) ; stores the last cons cell
    (declare (optimize (speed 3) (safety 0)))
    (loop for i from 1 below sup
          for cell = (list 1)
          do (setf (aref result i) cell
                   (aref tails i) cell))
    (when (>= sup 1)
      (setf (aref result 0) nil))
    (loop for divisor from 2 below sup
          do (loop for number from divisor below sup by divisor
                   do (setf (cdr (aref tails number)) (list divisor)
                            (aref tails number) (cdr (aref tails number)))))
    result))

;; BEGIN_USE_PACKAGE
(eval-when (:compile-toplevel :load-toplevel :execute)
  (use-package :cp/divisor :cl-user))
(in-package :cl-user)

;;;
;;; Body
;;;

(defun main ()
  (let* ((n (read))
         (table (make-divisors-table (+ n 1))))
    (println (loop for i from 1 to n by 2
                   count (= (length (aref table i)) 8)))))

#-swank (main)

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

#+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* (or out (make-string-output-stream)))
         (res (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))))))
    (if out res (get-output-stream-string *standard-output*))))

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

#-swank
(eval-when (:compile-toplevel)
  (when (and (boundp 'sb-c::*compiler-warning-count*)
             (> sb-c::*compiler-warning-count* 0))
    (sb-ext:quit :unix-status 1)))

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (5am:is
   (equal "1
"
          (run "105
" nil)))
  (5am:is
   (equal "0
"
          (run "7
" nil))))

Score: 200 points

Problem Statement

The number 105 is quite special - it is odd but still it has eight divisors.
Now, your task is this: how many odd numbers with exactly eight positive divisors are there between 1 and N (inclusive)?

Constraints

N is an integer between 1 and 200 (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print the count.

Sample Input 1

105

Sample Output 1

1

Among the numbers between 1 and 105, the only number that is odd and has exactly eight divisors is 105.

Sample Input 2

7

Sample Output 2

0

1 has one divisor. 3, 5 and 7 are all prime and have two divisors. Thus, there is no number that satisfies the condition.


(defun main ()
  (count 8 (mapcar #'kn (loop :for a :from 1 :upto (read) :by 2 collect a))))
(defun kn (n)
  (loop :for k :from 1 :upto n count(= (mod n k) 0)))
(format t "~A" (main))


(format t "~A" (count 8 (mapcar #'kn (loop :for a :from 1 :upto (read) collect a))))
(defun kn (n)
  (loop :for k :from 2 :upto n count(= (mod n k) 0)))


(defun solve (s k &optional (cnt 0))
  (cond
    ((= cnt k) 1)
    ((not (equal (first s) #\1)) (first s))
    (t (solve (rest s)
              k
              (1+ cnt)))))

(defun main ()
  (let ((s (concatenate 'list (read-line)))
        (k (read)))
    (princ (solve s k))
    (fresh-line)))

(main)

Score: 300 points

Problem Statement

Mr. Infinity has a string S consisting of digits from 1 to 9. Each time the date changes, this string changes as follows:

Each occurrence of 2 in S is replaced with 22. Similarly, each 3 becomes 333, 4 becomes 4444, 5 becomes 55555, 6 becomes 666666, 7 becomes 7777777, 8 becomes 88888888 and 9 becomes 999999999. 1 remains as 1.

For example, if S is 1324, it becomes 1333224444 the next day, and it becomes 133333333322224444444444444444 the day after next.
You are interested in what the string looks like after 5 \times 10^{15} days. What is the K-th character from the left in the string after 5 \times 10^{15} days?

Constraints

S is a string of length between 1 and 100 (inclusive).

K is an integer between 1 and 10^{18} (inclusive).

The length of the string after 5 \times 10^{15} days is at least K.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the K-th character from the left in Mr. Infinity's string after 5 \times 10^{15} days.

Sample Input 1

1214
4

Sample Output 1

2

The string S changes as follows:

Now: 1214

After one day: 12214444

After two days: 1222214444444444444444

After three days: 12222222214444444444444444444444444444444444444444444444444444444444444444

The first five characters in the string after 5 \times 10^{15} days is 12222. As K=4, we should print the fourth character, 2.

Sample Input 2

3
157

Sample Output 2

3

The initial string is 3. The string after 5 \times 10^{15} days consists only of 3.

Sample Input 3

299792458
9460730472580800

Sample Output 3

2