(defun card-game-for-two (n a)
  (let ((alice 0)
        (bob 0))
    (setf a (sort a #'>))
    (dotimes (i n)
      (if (zerop (rem i 2))
          (setf alice (+ alice (aref a i)))
          (setf bob (+ bob (aref a i)))))
    (- alice bob)))

(defun create-data ()
  (let* ((n (read))
         (a (make-array `(,n))))
    (dotimes (i n)
      (setf (aref a i) (read)))
    (values n a)))

(multiple-value-bind (n a) (create-data)
  (format t "~A~%" (card-game-for-two n a)))

Score : 200 points

Problem Statement

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

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

Constraints

1 ≤ N ≤ 100

1 ≤ d_i ≤ 100

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
d_1
:
d_N

Output

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

Sample Input 1

4
10
8
8
6

Sample Output 1

3

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

Sample Input 2

3
15
15
15

Sample Output 2

1

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

Sample Input 3

7
50
30
50
100
50
80
30

Sample Output 3

4


(defun solver ()
  (let* ((n (read)) (d (make-array n :fill-pointer 0)) (count 1))
    (loop repeat n do
          (vector-push (read) d))
    (sort d #'<)
    (loop for i from 0 to (- n 2) do
          (when (< (aref d i) (aref d (1+ i)))
            (incf count)))
    (format t "~a~%" count)))

(solver)

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

Submitted source-code file size, in bytes.

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

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


(print (length (remove-duplicates (loop repeat (read) collect (read)))))


Score : 100 points

Problem Statement

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

Constraints

1≤M≤23

M is an integer.

Input

Input is given from Standard Input in the following format:

M

Output

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

Sample Input 1

21

Sample Output 1

27

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

Sample Input 2

12

Sample Output 2

36


(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 ((a (read)))
    (println (+ 24 (- 24 a)))))

#-swank(main)


(defun solver ()
  (let ((a (read)) (b (read))
        (s (read-line)))
    (if (and (parse-integer s :start 0 :end a :junk-allowed t)
             (char= (char s a) #\-)
             (parse-integer s :start (+ a 1) :end (+ a b 1) :junk-allowed t))
        (format t "Yes~%")
        (format t "No~%"))))

(solver)

Score : 200 points

Problem Statement

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

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

Constraints

1≤A,B≤5

|S|=A+B+1

S consists of - and digits from 0 through 9.

Input

Input is given from Standard Input in the following format:

A B
S

Output

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

Sample Input 1

3 4
269-6650

Sample Output 1

Yes

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

Sample Input 2

1 1
---

Sample Output 2

No

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

Sample Input 3

1 2
7444

Sample Output 3

No


(let ((a (read))
      (b (read))
      (s (read-line)))
  (princ
   (if (and (= (length s) (+ a b 1))
            (char= (aref s a) #\-)
            (not (member #\- (concatenate 'list
                                          (subseq s 0 a)
                                          (subseq s (1+ a) (+ a b 1))))))
       "Yes"
       "No"))
  (terpri))


(let ((l (+ (read) (read)))
      (r (+ (read) (read))))

  (format t "~A~%"
          (cond ((= l r) "Balanced")
                ((< l r) "Right")
                (t "Left"))))

Score : 100 points

Problem Statement

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

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

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

Constraints

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

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

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

Sample Input 1

3 8 7 1

Sample Output 1

Left

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

Sample Input 2

3 4 5 2

Sample Output 2

Balanced

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

Sample Input 3

1 7 6 4

Sample Output 3

Right

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


(let ( (left (+ (read) (read))) (right (+ (read) (read))) )
     (format t "~a~%"
             (cond
               ((= left right)
                "Balanced")
               ((< left right)
                "Right")
               (t
                "Left")))
     )


(let ((a (read))
      (b (read))
      (ans 1))
  (setf b (floor (/ b a)))
  (loop for i from 1 while (<= (expt 2 i) b) do (incf ans))
  (format t "~A~%" ans))

Score : 300 points

Problem Statement

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

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

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

Find the maximum possible length of the sequence.

Constraints

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

All input values are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the maximum possible length of the sequence.

Sample Input 1

3 20

Sample Output 1

3

The sequence 3,6,18 satisfies the conditions.

Sample Input 2

25 100

Sample Output 2

3

Sample Input 3

314159265 358979323846264338

Sample Output 3

31


(defun solver ()
  (let ((x (read)) (y (read)) (count 0))
    (loop do
          (if (< y x)
              (return (format t "~a~%" count))
              (progn (setf x (* x 2)) (incf count))))))

(solver)


(let ((x (read))
      (y (read)))
  (format t "~A~%"
          (loop for i = x then (* 2 i)
                until (< y i)
                count i)))


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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

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

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

#-swank(main)

Score : 500 points

Problem Statement

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

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

Constraints

1\leq |S|\leq 10^5

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

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

010

Sample Output 1

2

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

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

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

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

Sample Input 2

100000000

Sample Output 2

8

Sample Input 3

00001111

Sample Output 3

4


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

;; BEGIN_INSERTED_CONTENTS
;;;
;;; ARRAY-ELEMENT-TYPE is not constant-folded on SBCL version earlier than
;;; 1.5.0. See
;;; https://github.com/sbcl/sbcl/commit/9f0d12e7ab961828931d01c0b2a76a5885ad35d2
;;;

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

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

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

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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(declaim (inline to-code))
(defun to-code (c)
  (- (char-code c) #.(char-code #\a)))

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

(defun solve-even (s)
  (declare (simple-base-string s))
  (let* ((len (length s))
         (len/2 (floor len 2))
         (histo (make-histogram s))
         (histo1 (make-array 26 :element-type 'uint32 :initial-element 0))
         (histo2 (make-array 26 :element-type 'uint32 :initial-element 0))
         (in-left (make-array len :fill-pointer 0))
         (to-right (make-array len :fill-pointer 0))
         (in-right (make-array len :fill-pointer 0))
         (to-left (make-array len :fill-pointer 0))
         (difference 0)
         (res 0))
    (declare (uint62 difference res))
    (assert (evenp len))
    (dotimes (i len/2 (fill histo1 0))
      (let* ((c (aref s i))
             (code (to-code c)))
        (incf (aref histo1 code))
        (when (> (aref histo1 code) (floor (aref histo code) 2))
          (incf difference))))
    (let ((delta difference))
      (declare (uint62 delta))
      (dotimes (i len/2)
        (let* ((c (aref s i))
               (code (to-code c)))
          (incf (aref histo1 code))
          (if (> (aref histo1 code) (floor (aref histo code) 2))
              (progn
                (vector-push (cons c i) to-right)
                (incf res (- (- len/2 delta) i))
                (decf delta))
              (vector-push (cons c i) in-left)))))
    (let ((delta difference))
      (declare (uint62 delta))
      (loop for i from (- len 1) downto len/2
            do (let* ((c (aref s i))
                      (code (to-code c)))
                 (incf (aref histo2 code))
                 (if (> (aref histo2 code) (floor (aref histo code) 2))
                     (progn
                       (vector-push (cons c i) to-left)
                       (incf res (- i (+ len/2 delta -1)))
                       (decf delta))
                     (vector-push (cons c i) in-right)))
            finally (setq to-left (nreverse to-left)
                          in-right (nreverse in-right))))
    (assert (= (length to-right) (length to-left)))
    (incf res (expt (length to-right) 2))
    (let ((tmp-left (map 'simple-base-string #'car (concatenate 'simple-vector in-left to-left)))
          (tmp-right (map 'simple-base-string #'car (concatenate 'simple-vector to-right in-right)))
          (ords (make-array 26 :element-type 'list :initial-element nil)))
      (loop for i from (- len/2 1) downto 0
            for ord from 0 below len/2
            do (push ord (aref ords (to-code (aref tmp-left i)))))
      (dotimes (i 26)
        (setf (aref ords i) (nreverse (aref ords i))))
      (let ((ord-right (map '(simple-array uint32 (*))
                            (lambda (c)
                              (pop (aref ords (to-code c))))
                            tmp-right)))
        (incf res (count-inversions! ord-right #'<)))
      res)))

(defun main ()
  (let* ((s (coerce (read-line) 'simple-base-string))
         (len (length s))
         (len/2 (floor len 2))
         (histo (make-histogram s)))
    (println
     (if (evenp len)
         (if (every #'evenp histo)
             (solve-even s)
             -1)
         (let ((odd-chars (loop for i below 26
                                for x across histo
                                when (oddp x)
                                collect (code-char (+ 97 i)))))
           (if (= (length odd-chars) 1)
               (let* ((odd-char (car odd-chars))
                      (pos0 (or (position odd-char s :end len/2 :from-end t)
                                most-negative-fixnum))
                      (pos1 (or (position odd-char s :start len/2)
                                most-positive-fixnum))
                      (pos (if (<= (- len/2 pos0) (- pos1 len/2))
                               pos0
                               pos1))
                      (s (concatenate 'simple-base-string
                                      (subseq s 0 pos)
                                      (subseq s (+ pos 1))))
                      (res (min (- len/2 pos0) (- pos1 len/2))))
                 (+ res (solve-even s)))
               -1))))))

#-swank (main)

Score : 800 points

Problem Statement

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

Constraints

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

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

eel

Sample Output 1

1

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

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

Sample Input 2

ataatmma

Sample Output 2

4

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

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

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

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

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

Sample Input 3

snuke

Sample Output 3

-1

We cannot turn S into a palindrome.


(format t "~A~%"
        (ceiling (/ (+ (read) (read)) 2)))

Score : 100 points

Problem Statement

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

Constraints

a and b are integers.

1 \leq a, b \leq 100

Input

Input is given from Standard Input in the following format:

a b

Output

Print x rounded up to the nearest integer.

Sample Input 1

1 3

Sample Output 1

2

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

Sample Input 2

7 4

Sample Output 2

6

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

Sample Input 3

5 5

Sample Output 3

5


(let ((a (read))
      (b (read)))
  (format t "~A~%" (truncate (+ a b 1) 2)))


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

Score : 200 points

Problem Statement

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

Notes

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

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

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

For example, xy < xya and atcoder < atlas.

Constraints

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

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

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

Sample Input 1

yx
axy

Sample Output 1

Yes

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

Sample Input 2

ratcode
atlas

Sample Output 2

Yes

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

Sample Input 3

cd
abc

Sample Output 3

No

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

Sample Input 4

w
ww

Sample Output 4

Yes

Sample Input 5

zzz
zzz

Sample Output 5

No


(defun answer (l r)
  (let ((ll (sort l #'char<))
	(rr (sort r #'char>)))
    (if (string< ll rr)
	"Yes"
	"No")))

(print (answer (read-line) (read-line)))


(defun tl (d)
  (let ((nd (1+ d)))
    (if (< 3 nd) 0 nd)))

(defun tr (d)
  (let ((nd (1- d)))
    (if (< nd 0) 3 nd)))

(defun move (x y d)
  (case d
    (0 (values (1+ x) y))
    (1 (values x (1- y)))
    (2 (values (1- x) y))
    (3 (values x (1+ y)))))

(defun dfs (s sidx slen gx gy x y d)
  (if (< sidx slen)
      (case (char s sidx)
        (#\F
         (multiple-value-setq (x y) (move x y d))
         (dfs s (1+ sidx) slen gx gy x y d))
        (#\T
         (or (dfs s (1+ sidx) slen gx gy x y (tl d))
             (dfs s (1+ sidx) slen gx gy x y (tr d)))))
      (when (and (= gx x)
                 (= gy y))
        t)))

(let ((s (read-line))
      (gx (read))
      (gy (read)))
  (format t "~A~%"
          (if (dfs s 0 (length s) gx gy 0 0 0)
              "Yes" "No")))

Score : 500 points

Problem Statement

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

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

F : Move in the current direction by distance 1.

T : Turn 90 degrees, either clockwise or counterclockwise.

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

Constraints

s consists of F and T.

1 \leq |s| \leq 8 000

x and y are integers.

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

Input

Input is given from Standard Input in the following format:

s
x y

Output

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

Sample Input 1

FTFFTFFF
4 2

Sample Output 1

Yes

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

Sample Input 2

FTFFTFFF
-2 -2

Sample Output 2

Yes

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

Sample Input 3

FF
1 0

Sample Output 3

No

Sample Input 4

TF
1 0

Sample Output 4

No

Sample Input 5

FFTTFF
0 0

Sample Output 5

Yes

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

Sample Input 6

TTTT
1 0

Sample Output 6

No


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

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

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

(defconstant +trie-alphabet-size+ 2)

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

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

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

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

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

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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

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

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

#-swank (main)

Score : 700 points

Problem Statement

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

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

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

Any two distinct strings in S are prefix-free.

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

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

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

Constraints

1 \leq N \leq 10^5

1 \leq L \leq 10^{18}

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

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

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

Input

Input is given from Standard Input in the following format:

N L
s_1
s_2
:
s_N

Output

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

Sample Input 1

2 2
00
01

Sample Output 1

Alice

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

Sample Input 2

2 2
00
11

Sample Output 2

Bob

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

Sample Input 3

3 3
0
10
110

Sample Output 3

Alice

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

Sample Input 4

2 1
0
1

Sample Output 4

Bob

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

Sample Input 5

1 2
11

Sample Output 5

Alice

Sample Input 6

2 3
101
11

Sample Output 6

Bob


(defun shift-only (n a)
  (let ((res 0)
	(exist-odd nil))
    (loop
      ;; (dotimes (i n)
      ;; 	(if (not (zerop (rem (aref a i) 2)))
      ;; 	    (setf exist-odd t)))
      (if (oddp (apply #'+ a;; (coerce temp 'list)
		       ))
	  (setf exist-odd t))
      (if (eq exist-odd t) (return))
      (dotimes (i n)
	;; (setf (aref a i) (/ (aref a i) 2))
	((setf (nth i a) (/ (nth i a) 2))))
      (incf res))
    res))

(defun create-data ()
  (let* ((n (read))
	 (a ;; (make-array `(,n))
	   (loop for i to (- n 1) collect i)))
    (dotimes (i n)
      ;; (setf (aref a i) (read))
      (setf (nth i a) (read)))
    (values n a)))
;; (create-data)

(multiple-value-bind (n a) (create-data)
  (format t "~a~%" (shift-only n a)))

Score : 200 points

Problem Statement

There are N positive integers written on a blackboard: A_1, ..., A_N.

Snuke can perform the following operation when all integers on the blackboard are even:

Replace each integer X on the blackboard by X divided by 2.

Find the maximum possible number of operations that Snuke can perform.

Constraints

1 \leq N \leq 200

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 maximum possible number of operations that Snuke can perform.

Sample Input 1

3
8 12 40

Sample Output 1

2

Initially, [8, 12, 40] are written on the blackboard.
Since all those integers are even, Snuke can perform the operation.

After the operation is performed once, [4, 6, 20] are written on the blackboard.
Since all those integers are again even, he can perform the operation.

After the operation is performed twice, [2, 3, 10] are written on the blackboard.
Now, there is an odd number 3 on the blackboard, so he cannot perform the operation any more.

Thus, Snuke can perform the operation at most twice.

Sample Input 2

4
5 6 8 10

Sample Output 2

0

Since there is an odd number 5 on the blackboard already in the beginning, Snuke cannot perform the operation at all.

Sample Input 3

6
382253568 723152896 37802240 379425024 404894720 471526144

Sample Output 3

8


(defun odd-helper (n)
  (find-if #'oddp n))

(defun zero-helper (n)
  (find-if #'zerop n))

(defun main (&rest n)
  (shiftonly 0 n))

(defun shiftonly (ans lis)
  (if (odd-helper lis)
      (format t "~a~%" ans)
      (if (zero-helper lis)
          (format t "~a~%" ans)
          (shiftonly (+ 1 ans) (mapcar #'(lambda (x) (/ x 2)) lis)))))

(read)
(main (read))


(defun group-and-rest (lst k)
  (cond
    ((null lst) lst)
    ((= 0 k) lst)
    ((not (equal (first lst) (second lst)))
     (group-and-rest (cdr lst) (1- k)))
    (t
     (group-and-rest (cdr lst) k))))

(defun read-input (N)
  (sort (loop for n from 1 upto N collect (read))
        #'<))

(defun main ()
  (let ((N (read)) (K (read)))
    (format t "~a~%"
            (length (group-and-rest (read-input N) K)))))
(main)

Score : 300 points

Problem Statement

Takahashi has N balls. Initially, an integer A_i is written on the i-th ball.

He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls.

Find the minimum number of balls that Takahashi needs to rewrite the integers on them.

Constraints

1 \leq K \leq N \leq 200000

1 \leq A_i \leq N

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

Print the minimum number of balls that Takahashi needs to rewrite the integers on them.

Sample Input 1

5 2
1 1 2 2 5

Sample Output 1

1

For example, if we rewrite the integer on the fifth ball to 2, there are two different integers written on the balls: 1 and 2.
On the other hand, it is not possible to rewrite the integers on zero balls so that there are at most two different integers written on the balls, so we should print 1.

Sample Input 2

4 4
1 1 2 2

Sample Output 2

0

Already in the beginning, there are two different integers written on the balls, so we do not need to rewrite anything.

Sample Input 3

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

Sample Output 3

3


(let ((n (read))
    (k (read))
    (a (make-array 200000))
    (ans 0))
    (loop for i below n do
        (incf (aref a (read)))
    )
    (setf a (delete-if (lambda (x) (= x 0)) a))
    (sort a '<)
    (if (> (- (length a) k) 0)
        (setq ans (loop for i across (subseq a 0 (- (length a) k)) sum i))
    )
    (format t "~d~%" ans)
)


(let ((n (read))
      (a (read))
      (b (read)))
  (format t "~A~%"
          (min (* n a)
               b)))

Score : 100 points

Problem Statement

You are parking at a parking lot. You can choose from the following two fee plans:

Plan 1: The fee will be A×T yen (the currency of Japan) when you park for T hours.

Plan 2: The fee will be B yen, regardless of the duration.

Find the minimum fee when you park for N hours.

Constraints

1≤N≤20

1≤A≤100

1≤B≤2000

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

When the minimum fee is x yen, print the value of x.

Sample Input 1

7 17 120

Sample Output 1

119

If you choose Plan 1, the fee will be 7×17=119 yen.

If you choose Plan 2, the fee will be 120 yen.

Thus, the minimum fee is 119 yen.

Sample Input 2

5 20 100

Sample Output 2

100

The fee might be the same in the two plans.

Sample Input 3

6 18 100

Sample Output 3

100


(let* ((n (read-line))
       (fx (loop for ch across n sum (- (char-code ch) (char-code #\0)))))
  (if (= 0 (mod (parse-integer n) fx))
      (format t "Yes~%")
      (format t "No~%")))

Score : 200 points

Problem Statement

An integer X is called a Harshad number if X is divisible by f(X), where f(X) is the sum of the digits in X when written in base 10.

Given an integer N, determine whether it is a Harshad number.

Constraints

1?N?10^8

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print Yes if N is a Harshad number; print No otherwise.

Sample Input 1

12

Sample Output 1

Yes

f(12)=1+2=3. Since 12 is divisible by 3, 12 is a Harshad number.

Sample Input 2

57

Sample Output 2

No

f(57)=5+7=12. Since 57 is not divisible by 12, 12 is not a Harshad number.

Sample Input 3

148

Sample Output 3

No


(let* ((n (read-line))
       (fx (loop for ch across n sum (- (char-code ch) (char-code #\0)))))
  (if (= 0 (mod (parse-integer n) fx))
      (format t "Yes~%")
      (format t "NO~&")))


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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (let* ((n (read))
         (fs (make-array (list n 10) :element-type 'bit :initial-element 0))
         (ps (make-array (list n 11) :element-type 'int32 :initial-element 0)))
    (dotimes (i n)
      (dotimes (j 10)
        (setf (aref fs i j) (read))))
    (dotimes (i n)
      (dotimes (j 11)
        (setf (aref ps i j) (read))))
    (println
     (loop
       for bits from 1 below (expt 2 10)
       maximize (loop for i below n
                      for cumul = (loop
                                    for j below 10
                                    sum (logand (aref fs i j)
                                                (ldb (byte 1 j) bits)))
                      sum (aref ps i cumul))))))

#-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 "C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe" '("get-clipboard") :output 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 "1
1 1 0 1 0 0 0 1 0 1
3 4 5 6 7 8 9 -2 -3 4 -2
"
    "8
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
"
    "-2
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
1 1 1 1 1 1 0 0 1 1
0 1 0 1 1 1 1 0 1 0
1 0 1 1 0 1 0 1 0 1
-8 6 -2 -8 -8 4 8 7 -6 2 2
-9 2 0 1 7 -5 0 -2 -6 5 5
6 -6 7 -9 6 -5 8 0 -9 -7 -7
"
    "23
")))

Score : 300 points

Problem Statement

Joisino is planning to open a shop in a shopping street.

Each of the five weekdays is divided into two periods, the morning and the evening. For each of those ten periods, a shop must be either open during the whole period, or closed during the whole period. Naturally, a shop must be open during at least one of those periods.

There are already N stores in the street, numbered 1 through N.

You are given information of the business hours of those shops, F_{i,j,k}. If F_{i,j,k}=1, Shop i is open during Period k on Day j (this notation is explained below); if F_{i,j,k}=0, Shop i is closed during that period. Here, the days of the week are denoted as follows. Monday: Day 1, Tuesday: Day 2, Wednesday: Day 3, Thursday: Day 4, Friday: Day 5. Also, the morning is denoted as Period 1, and the afternoon is denoted as Period 2.

Let c_i be the number of periods during which both Shop i and Joisino's shop are open. Then, the profit of Joisino's shop will be P_{1,c_1}+P_{2,c_2}+...+P_{N,c_N}.

Find the maximum possible profit of Joisino's shop when she decides whether her shop is open during each period, making sure that it is open during at least one period.

Constraints

1≤N≤100

0≤F_{i,j,k}≤1

For every integer i such that 1≤i≤N, there exists at least one pair (j,k) such that F_{i,j,k}=1.

-10^7≤P_{i,j}≤10^7

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
F_{1,1,1} F_{1,1,2} ... F_{1,5,1} F_{1,5,2}
:
F_{N,1,1} F_{N,1,2} ... F_{N,5,1} F_{N,5,2}
P_{1,0} ... P_{1,10}
:
P_{N,0} ... P_{N,10}

Output

Print the maximum possible profit of Joisino's shop.

Sample Input 1

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

Sample Output 1

8

If her shop is open only during the periods when Shop 1 is opened, the profit will be 8, which is the maximum possible profit.

Sample Input 2

2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1

Sample Output 2

-2

Note that a shop must be open during at least one period, and the profit may be negative.

Sample Input 3

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

Sample Output 3

23


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

;; BEGIN_INSERTED_CONTENTS
(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
                                  ;; (return-from read-fixnum 0)
                                  (error "Read EOF or #\Nul."))
                                 ((= byte #.(char-code #\-))
                                  (setf minus t)))))))
      (declare ((integer 0 #.most-positive-fixnum) result))
      (loop
        (let* ((byte (%read-byte)))
          (if (<= 48 byte 57)
              (setq result (+ (- byte 48) (* 10 (the (integer 0 #.(floor most-positive-fixnum 10)) result))))
              (return (if minus (- result) result))))))))

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (let* ((n (read))
         (c (read))
         (timeline (make-array 100002 :element-type 'int32 :initial-element 0)))
    (declare (uint32 n) (ignore c))
    (dotimes (i n)
      (let ((begin (read-fixnum))
            (end (+ (read-fixnum) 1))
            (channel (read-fixnum)))
        (declare (ignore channel))
        (incf (aref timeline begin))
        (decf (aref timeline end))))
    (dotimes (i 100001)
      (incf (aref timeline (+ i 1)) (aref timeline i)))
    (println (reduce #'max timeline))))

#-swank(main)

Score : 400 points

Problem Statement

Joisino is planning to record N TV programs with recorders.

The TV can receive C channels numbered 1 through C.

The i-th program that she wants to record will be broadcast from time s_i to time t_i (including time s_i but not t_i) on Channel c_i.

Here, there will never be more than one program that are broadcast on the same channel at the same time.

When the recorder is recording a channel from time S to time T (including time S but not T), it cannot record other channels from time S-0.5 to time T (including time S-0.5 but not T).

Find the minimum number of recorders required to record the channels so that all the N programs are completely recorded.

Constraints

1≤N≤10^5

1≤C≤30

1≤s_i<t_i≤10^5

1≤c_i≤C

If c_i=c_j and i≠j, either t_i≤s_j or s_i≥t_j.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N C
s_1 t_1 c_1
:
s_N t_N c_N

Output

When the minimum required number of recorders is x, print the value of x.

Sample Input 1

3 2
1 7 2
7 8 1
8 12 1

Sample Output 1

2

Two recorders can record all the programs, for example, as follows:

With the first recorder, record Channel 2 from time 1 to time 7. The first program will be recorded. Note that this recorder will be unable to record other channels from time 0.5 to time 7.

With the second recorder, record Channel 1 from time 7 to time 12. The second and third programs will be recorded. Note that this recorder will be unable to record other channels from time 6.5 to time 12.

Sample Input 2

3 4
1 3 2
3 4 4
1 4 3

Sample Output 2

3

There may be a channel where there is no program to record.

Sample Input 3

9 4
56 60 4
33 37 2
89 90 3
32 43 1
67 68 3
49 51 3
31 32 3
70 71 1
11 12 3

Sample Output 3

2


(defparameter *N* (read-line))

(defparameter *larger* (truncate *N* 10))
(defparameter *smaller* (rem *N* 1000))

(cond ( (= (rem *larger* 37) 0) "YES")
      ( (= (rem *smaller* 37) 0) "YES")
      "NO")

Score : 100 points

Problem Statement

We call a 4-digit integer with three or more consecutive same digits, such as 1118, good.

You are given a 4-digit integer N. Answer the question: Is N good?

Constraints

1000 ≤ N ≤ 9999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is good, print Yes; otherwise, print No.

Sample Input 1

1118

Sample Output 1

Yes

N is good, since it contains three consecutive 1.

Sample Input 2

7777

Sample Output 2

Yes

An integer is also good when all the digits are the same.

Sample Input 3

1234

Sample Output 3

No


(defparameter *N* (read))

(defparameter *larger* (truncate *N* 10))
(defparameter *smaller* (rem *N* 1000))

(cond ( (= (rem *larger* 37) 0) "YES")
      ( (= (rem *smaller* 37) 0) "YES")
      "NO")


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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (let* ((n (map 'list #'digit-char-p (read-line))))
    (sb-int:named-let recur ((rest (cdr n)) (sum (car n)) (res (list (car n))))
      (if (null rest)
          (when (= sum 7)
            (map () #'princ (reverse res))
            (write-line "=7")
            (return-from main))
          (progn
            (recur (cdr rest) (+ sum (car rest)) `(,(car rest) #\+ ,@res))
            (recur (cdr rest) (- sum (car rest)) `(,(car rest) #\- ,@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 "1222
"
    "1+2+2+2=7
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "0290
"
    "0-2+9+0=7
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3242
"
    "3+2+4-2=7
")))

Score : 300 points

Problem Statement

Sitting in a station waiting room, Joisino is gazing at her train ticket.

The ticket is numbered with four digits A, B, C and D in this order, each between 0 and 9 (inclusive).

In the formula A op1 B op2 C op3 D = 7, replace each of the symbols op1, op2 and op3 with + or - so that the formula holds.

The given input guarantees that there is a solution. If there are multiple solutions, any of them will be accepted.

Constraints

0≤A,B,C,D≤9

All input values are integers.

It is guaranteed that there is a solution.

Input

Input is given from Standard Input in the following format:

ABCD

Output

Print the formula you made, including the part =7.

Use the signs + and -.

Do not print a space between a digit and a sign.

Sample Input 1

1222

Sample Output 1

1+2+2+2=7

This is the only valid solution.

Sample Input 2

0290

Sample Output 2

0-2+9+0=7

0 - 2 + 9 - 0 = 7 is also a valid solution.

Sample Input 3

3242

Sample Output 3

3+2+4-2=7


(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 buffered-read-line (&optional (buffer-size 30) (in '*standard-input*) (terminate-char #\Space))
  "Note that the returned string will be reused."
  (let ((buffer (gensym))
        (character (gensym))
        (idx (gensym)))
    `(let ((,buffer (load-time-value (make-string ,buffer-size
                                                  :element-type 'base-char))))
       (declare (simple-base-string ,buffer))
       (loop for ,character of-type base-char =
                #-swank (code-char (read-byte ,in nil #\Newline))
                #+swank (read-char ,in nil #\Newline)
             for ,idx from 0
             until (char= ,character #\Newline)
             do (setf (schar ,buffer ,idx) ,character)
             finally (setf (schar ,buffer ,idx) ,terminate-char)
                     (return (values ,buffer ,idx))))))

(declaim (inline split-integers-into-array))
(defun split-integers-into-array (string dest-array row &key (offset 0))
  (declare (string string)
           ((simple-array * (* *)) dest-array)
           ((integer 0 #.most-positive-fixnum) row offset))
  (loop for idx from offset below (array-dimension dest-array 1)
        for pos1 = 0 then (1+ pos2)
        for pos2 = (position #\space string :start pos1 :test #'char=)
        do (setf (aref dest-array row idx)
                 (parse-integer string :start pos1 :end pos2))
        finally (return dest-array)))

(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

(defun main ()
  (let* ((h (read))
         (w (read))
         (costs (make-array '(10 10) :element-type 'uint16))
         (wall (make-array (list h w) :element-type 'int16)))
    (dotimes (i 10)
      (split-integers-into-array (buffered-read-line 80) costs i))
    (dotimes (i h)
      (split-integers-into-array (buffered-read-line 800) wall i))
    (dotimes (k 10)
      (dotimes (i 10)
        (dotimes (j 10)
          (when (> (aref costs i j) (+ (aref costs i k) (aref costs k j)))
            (setf (aref costs i j) (+ (aref costs i k) (aref costs k j)))))))
    (println
     (loop for i below h
           sum (loop for j below w
                     sum (if (= -1 (aref wall i j))
                             0
                             (aref costs (aref wall i j) 1)))))))

#-swank(main)

Score : 400 points

Problem Statement

Joisino the magical girl has decided to turn every single digit that exists on this world into 1.

Rewriting a digit i with j (0≤i,j≤9) costs c_{i,j} MP (Magic Points).

She is now standing before a wall. The wall is divided into HW squares in H rows and W columns, and at least one square contains a digit between 0 and 9 (inclusive).

You are given A_{i,j} that describes the square at the i-th row from the top and j-th column from the left, as follows:

If A_{i,j}≠-1, the square contains a digit A_{i,j}.

If A_{i,j}=-1, the square does not contain a digit.

Find the minimum total amount of MP required to turn every digit on this wall into 1 in the end.

Constraints

1≤H,W≤200

1≤c_{i,j}≤10^3 (i≠j)

c_{i,j}=0 (i=j)

-1≤A_{i,j}≤9

All input values are integers.

There is at least one digit on the wall.

Input

Input is given from Standard Input in the following format:

H W
c_{0,0} ... c_{0,9}
:
c_{9,0} ... c_{9,9}
A_{1,1} ... A_{1,W}
:
A_{H,1} ... A_{H,W}

Output

Print the minimum total amount of MP required to turn every digit on the wall into 1 in the end.

Sample Input 1

2 4
0 9 9 9 9 9 9 9 9 9
9 0 9 9 9 9 9 9 9 9
9 9 0 9 9 9 9 9 9 9
9 9 9 0 9 9 9 9 9 9
9 9 9 9 0 9 9 9 9 2
9 9 9 9 9 0 9 9 9 9
9 9 9 9 9 9 0 9 9 9
9 9 9 9 9 9 9 0 9 9
9 9 9 9 2 9 9 9 0 9
9 2 9 9 9 9 9 9 9 0
-1 -1 -1 -1
8 1 1 8

Sample Output 1

12

To turn a single 8 into 1, it is optimal to first turn 8 into 4, then turn 4 into 9, and finally turn 9 into 1, costing 6 MP.

The wall contains two 8s, so the minimum total MP required is 6×2=12.

Sample Input 2

5 5
0 999 999 999 999 999 999 999 999 999
999 0 999 999 999 999 999 999 999 999
999 999 0 999 999 999 999 999 999 999
999 999 999 0 999 999 999 999 999 999
999 999 999 999 0 999 999 999 999 999
999 999 999 999 999 0 999 999 999 999
999 999 999 999 999 999 0 999 999 999
999 999 999 999 999 999 999 0 999 999
999 999 999 999 999 999 999 999 0 999
999 999 999 999 999 999 999 999 999 0
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

Sample Output 2

0

Note that she may not need to change any digit.

Sample Input 3

3 5
0 4 3 6 2 7 2 5 3 3
4 0 5 3 7 5 3 7 2 7
5 7 0 7 2 9 3 2 9 1
3 6 2 0 2 4 6 4 2 3
3 5 7 4 0 6 9 7 6 7
9 8 5 2 2 0 4 7 6 5
5 4 6 3 2 3 0 5 4 3
3 6 2 3 4 2 4 0 8 9
4 6 5 4 3 5 3 2 0 8
2 1 3 4 5 7 8 6 4 0
3 5 2 6 1
2 5 3 2 1
6 9 2 5 6

Sample Output 3

47


Score : 200 points

Problem Statement

We have a long seat of width X centimeters.
There are many people who wants to sit here. A person sitting on the seat will always occupy an interval of length Y centimeters.

We would like to seat as many people as possible, but they are all very shy, and there must be a gap of length at least Z centimeters between two people, and between the end of the seat and a person.

At most how many people can sit on the seat?

Constraints

All input values are integers.

1 \leq X, Y, Z \leq 10^5

Y+2Z \leq X

Input

Input is given from Standard Input in the following format:

X Y Z

Output

Print the answer.

Sample Input 1

13 3 1

Sample Output 1

3

There is just enough room for three, as shown below:

Figure

Sample Input 2

12 3 1

Sample Output 2

2

Sample Input 3

100000 1 1

Sample Output 3

49999

Sample Input 4

64146 123 456

Sample Output 4

110

Sample Input 5

64145 123 456

Sample Output 5

109


Score : 300 points

Problem Statement

Takahashi is now competing in a programming contest, but he received TLE in a problem where the answer is YES or NO.

When he checked the detailed status of the submission, there were N test cases in the problem, and the code received TLE in M of those cases.

Then, he rewrote the code to correctly solve each of those M cases with 1/2 probability in 1900 milliseconds, and correctly solve each of the other N-M cases without fail in 100 milliseconds.

Now, he goes through the following process:

Submit the code.

Wait until the code finishes execution on all the cases.

If the code fails to correctly solve some of the M cases, submit it again.

Repeat until the code correctly solve all the cases in one submission.

Let the expected value of the total execution time of the code be X milliseconds. Print X (as an integer).

Constraints

All input values are integers.

1 \leq N \leq 100

1 \leq M \leq {\rm min}(N, 5)

Input

Input is given from Standard Input in the following format:

N M

Output

Print X, the expected value of the total execution time of the code, as an integer. It can be proved that, under the constraints in this problem, X is an integer not exceeding 10^9.

Sample Input 1

1 1

Sample Output 1

3800

In this input, there is only one case. Takahashi will repeatedly submit the code that correctly solves this case with 1/2 probability in 1900 milliseconds.

The code will succeed in one attempt with 1/2 probability, in two attempts with 1/4 probability, and in three attempts with 1/8 probability, and so on.

Thus, the answer is 1900 \times 1/2 + (2 \times 1900) \times 1/4 + (3 \times 1900) \times 1/8 + ... = 3800.

Sample Input 2

10 2

Sample Output 2

18400

The code will take 1900 milliseconds in each of the 2 cases, and 100 milliseconds in each of the 10-2=8 cases. The probability of the code correctly solving all the cases is 1/2 \times 1/2 = 1/4.

Sample Input 3

100 5

Sample Output 3

608000


(let ((c1 (concatenate 'list (read-line)))
      (c2 (concatenate 'list (read-line))))

  (format t "~A~%"
          (if (equal (reverse c1) c2)
            'yes
            'no)))

Score : 100 points

Problem Statement

You are given a grid with 2 rows and 3 columns of squares.
The color of the square at the i-th row and j-th column is represented by the character C_{ij}.

Write a program that prints YES if this grid remains the same when rotated 180 degrees, and prints NO otherwise.

Constraints

C_{i,j}(1 \leq i \leq 2, 1 \leq j \leq 3) is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

C_{11}C_{12}C_{13}
C_{21}C_{22}C_{23}

Output

Print YES if this grid remains the same when rotated 180 degrees; print NO otherwise.

Sample Input 1

pot
top

Sample Output 1

YES

This grid remains the same when rotated 180 degrees.

Sample Input 2

tab
bet

Sample Output 2

NO

This grid does not remain the same when rotated 180 degrees.

Sample Input 3

eye
eel

Sample Output 3

NO


(if (equal
      (read-line)
      (reverse (read-line))
      )
    (format t "YES~%")
    (format t "NO~%")
    )


(let* ((a (read))
       (ans 1))
  (loop :while (<= (expt ans 2) a) :do(setf ans (1+ ans)))
  (princ (expt (1- ans) 2)))

Score : 200 points

Problem Statement

Find the largest square number not exceeding N. Here, a square number is an integer that can be represented as the square of an integer.

Constraints

1 \leq N \leq 10^9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the largest square number not exceeding N.

Sample Input 1

10

Sample Output 1

9

10 is not square, but 9 = 3 × 3 is. Thus, we print 9.

Sample Input 2

81

Sample Output 2

81

Sample Input 3

271828182

Sample Output 3

271821169


(defun lower-bound (predicate &optional (ok 0) (ng (expt 10 10)))
  (if (<= (abs (- ng ok)) 1)
      ok
      (let ((mid (floor (+ ng ok) 2)))
        (if (funcall predicate mid)
            (lower-bound predicate mid ng)
            (lower-bound predicate ok mid)))))

(defun smaller-p (xs index b-size)
  (< (aref xs index) b-size))

(defun bigger-p (xs index b-size)
  (> (aref xs index) b-size))

(defun solve (a b c &optional (res 0))
  (declare (optimize speed))
  (declare (type (array fixnum) a b c))
  (declare (type integer res))
  (the integer
       (dotimes (j (length b) res)
         (incf res (* (lower-bound #'(lambda (x)
                                       (smaller-p a x (aref b j)))
                                   0
                                   (length a))
                      (lower-bound #'(lambda (x)
                                       (bigger-p c x (aref b j)))
                                   0
                                   (length c)))))))

(defparameter *inf* (1+ (expt 10 9)))

(locally
  (declare (inline sort))
  (let* ((n (read))
         (a (make-array (1+ n) :element-type 'fixnum))
         (b (make-array n      :element-type 'fixnum))
         (c (make-array (1+ n) :element-type 'fixnum)))
    (declare (type fixnum n))
    (setf (aref a (1- (length a))) 0)
    (setf (aref c (1- (length c))) *inf*)
    (dotimes (i n)
      (setf (aref a i) (read)))
    (dotimes (i n)
      (setf (aref b i) (read)))
    (dotimes (i n)
      (setf (aref c i) (read)))
    (sort a #'<)
    (sort c #'>)
    (princ (solve a b c))
    (fresh-line)))

Score : 300 points

Problem Statement

The season for Snuke Festival has come again this year. First of all, Ringo will perform a ritual to summon Snuke. For the ritual, he needs an altar, which consists of three parts, one in each of the three categories: upper, middle and lower.

He has N parts for each of the three categories. The size of the i-th upper part is A_i, the size of the i-th middle part is B_i, and the size of the i-th lower part is C_i.

To build an altar, the size of the middle part must be strictly greater than that of the upper part, and the size of the lower part must be strictly greater than that of the middle part. On the other hand, any three parts that satisfy these conditions can be combined to form an altar.

How many different altars can Ringo build? Here, two altars are considered different when at least one of the three parts used is different.

Constraints

1 \leq N \leq 10^5

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

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

1 \leq C_i \leq 10^9(1\leq i\leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N
B_1 ... B_N
C_1 ... C_N

Output

Print the number of different altars that Ringo can build.

Sample Input 1

2
1 5
2 4
3 6

Sample Output 1

3

The following three altars can be built:

Upper: 1-st part, Middle: 1-st part, Lower: 1-st part

Upper: 1-st part, Middle: 1-st part, Lower: 2-nd part

Upper: 1-st part, Middle: 2-nd part, Lower: 2-nd part

Sample Input 2

3
1 1 1
2 2 2
3 3 3

Sample Output 2

27

Sample Input 3

6
3 14 159 2 6 53
58 9 79 323 84 6
2643 383 2 79 50 288

Sample Output 3

87


(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 bisect-left))
(defun bisect-left (target value &key (start 0) end (test #'<) (key #'identity))
  "TARGET := vector | function
TEST := strict order

Returns the smallest index (or input) i that fulfills TARGET[i] >= VALUE, where
'>=' is the complement of TEST. TARGET must be monotonically non-decreasing with
respect to TEST. Returns END if VALUE exceeds TARGET[END-1]. Note that the range
[START, END) is half-open. END must be specified If TARGET is function. KEY is
applied to each element of TARGET before comparison."
  (declare (function key test)
           ((integer 0 #.most-positive-fixnum) start)
           ((or null (integer 0 #.most-positive-fixnum)) end))
  (macrolet
      ((body (accessor &optional declaration)
         `(cond ((assert (<= start end)))
                ((= start end) end)
                ((funcall test (funcall key (,accessor target (- end 1))) value)
                 end)
                (t (labels ((%bisect-left (l r)
                              ,@(list declaration)
                              (let ((mid (floor (+ l r) 2)))
                                (if (= mid l)
                                    (if (funcall test (funcall key (,accessor target l)) value)
                                        r
                                        l)
                                    (if (funcall test (funcall key (,accessor target mid)) value)
                                        (%bisect-left mid r)
                                        (%bisect-left l mid))))))
                     (%bisect-left start (- end 1)))))))
    (etypecase target
      (vector
       (let ((end (or end (length target))))
         (body aref (declare ((integer 0 #.most-positive-fixnum) l r)))))
      (function
       (assert end)
       (body funcall)))))

(declaim (inline bisect-right))
(defun bisect-right (target value &key (start 0) end (test #'<) (key #'identity))
  "TARGET := vector | function
TEST := strict order

Returns the smallest index (or input) i that fulfills TARGET[i] > VALUE. TARGET
must be monotonically non-decreasing with respect to TEST. Returns END if VALUE
exceeds TARGET[END-1]. Note that the range [START, END) is half-open. END must
be specified if TARGET is function. KEY is applied to each element of TARGET
before comparison."
  (declare (function key test)
           ((integer 0 #.most-positive-fixnum) start)
           ((or null (integer 0 #.most-positive-fixnum)) end))
  (macrolet
      ((body (accessor &optional declaration)
         `(cond ((assert (<= start end)))
                ((= start end) end)
                ((funcall test value (funcall key (,accessor target (- end 1))))
                 (labels ((%bisect-right (l r)
                            ,@(list declaration)
                            (let ((mid (floor (+ l r) 2)))
                              (if (= mid l)
                                  (if (funcall test value (funcall key (,accessor target l)))
                                      l
                                      r)
                                  (if (funcall test value (funcall key (,accessor target mid)))
                                      (%bisect-right l mid)
                                      (%bisect-right mid r))))))

                   (%bisect-right start (- end 1))))
                (t end))))
    (etypecase target
      (vector
       (when (null end)
         (setf end (length target)))
       (body aref (declare ((integer 0 #.most-positive-fixnum) l r))))
      (function
       (assert end)
       (body funcall)))))

(declaim (inline read-line-into))
(defun read-line-into (buffer-string &key (in *standard-input*) (terminate-char #\Space))
  (declare (simple-base-string buffer-string))
  (loop for c of-type base-char =
           #-swank (code-char (read-byte in nil #\Newline))
           #+swank (read-char in nil #\Newline)
        for idx from 0
        until (char= c #\Newline)
        do (setf (schar buffer-string idx) c)
        finally (setf (schar buffer-string idx) terminate-char)
                (return (values buffer-string idx))))

(declaim (inline split-ints-into-vector))
(defun split-ints-into-vector (string dest-vector &key (offset 0) (key #'identity))
  (declare (string string)
           (function key)
           ((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)
                 (funcall key (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))))

(defconstant +mod+ 1000000007)

;; Hauptteil

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (as (make-array n :element-type 'uint32))
         (bs (make-array n :element-type 'uint32))
         (cs (make-array n :element-type 'uint32))
         (buf (make-string 1200000 :element-type 'base-char)))
    (dolist (seq (list as bs cs))
      (declare ((simple-array uint32 (*)) seq))
      (split-ints-into-vector (read-line-into buf) seq))
    (setf as (stable-sort as #'<)
          cs (stable-sort cs #'<))
    (println
     (loop for b across bs
           sum (* (the uint31 (bisect-left as b))
                  (the uint31 (- n (bisect-right cs b))))
           of-type fixnum))))

#-swank(main)


(defun split (string &key (delimiterp #'delimiterp))
  (loop :for beg = (position-if-not delimiterp string)
    :then (position-if-not delimiterp string :start (1+ end))
    :for end = (and beg (position-if delimiterp string :start beg))
    :when beg :collect (subseq string beg end)
    :while end))
(defun delimiterp (c) (position c " ,.;/"))

(defun make-array-from-list (l)
  (make-array (list (length l)) :initial-contents l)
  )

(defun bisect-left (n arr)
  (bisect-left_ n 0 (length arr) arr))
(defun bisect-left_ (n lo hi arr)
  (cond ((>= lo hi) (return-from bisect-left_ lo))
        (t
          (let ((mid (floor (/ (+ lo hi) 2))))
            (cond ((<= n (aref arr mid)) (return-from bisect-left_
                                                      (bisect-left_ n lo mid arr)))
                  (t (return-from bisect-left_ (bisect-left_ n (1+ mid) hi arr))))))
        ))

(defun bisect-right (n arr)
  (bisect-right_ n 0 (length arr) arr))
(defun bisect-right_ (n lo hi arr)
  (cond ((>= lo hi) (return-from bisect-right_ hi))
        (t
          (let ((mid (floor (/ (+ lo hi) 2))))
            (cond ((< n (aref arr mid)) (return-from bisect-right_
                                                      (bisect-right_ n lo mid arr)))
                  (t (return-from bisect-right_ (bisect-right_ n (1+ mid) hi arr))))))
        ))

(defun main()
  (let ((n (read))
        (as (sort (make-array-from-list (map 'list #'parse-integer (split (read-line)))) #'<))
        (bs (map 'list #'parse-integer (split (read-line))))
        (cs (sort (make-array-from-list (map 'list #'parse-integer (split (read-line)))) #'<))
        )

    (princ (reduce #'+ (loop :for b :in bs :collect
                       (* (bisect-left b as) (- n (bisect-right b cs))))))
    (princ #\newline)
    )
)
(main)


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

;; BEGIN_INSERTED_CONTENTS
;;;
;;; Real FFT
;;;
;;; Reference:
;;; http://www.kurims.kyoto-u.ac.jp/~ooura/fftman/ftmn2_12.html#sec2_1_2
;;;

(deftype fft-float () 'single-float)

(declaim (inline power2-p))
(defun power2-p (x)
  "Checks if X is a power of 2."
  (zerop (logand x (- x 1))))

;; For FFT of fixed length, preparing the table of cos(i*theta) and sin
;; (i*theta) will be efficient.
(defun %make-trifunc-table (n)
  (declare (optimize (speed 3))
           ((integer 0 #.most-positive-fixnum) n))
  (assert (power2-p n))
  (let* ((cos-table (make-array (ash n -2) :element-type 'fft-float))
         (sin-table (make-array (ash n -2) :element-type 'fft-float))
         (theta (/ (coerce (* 2 pi) 'fft-float) n)))
    (dotimes (i (ash n -2))
      (setf (aref cos-table i) (cos (* i theta))
            (aref sin-table i) (sin (* i theta))))
    (values cos-table sin-table)))

(defparameter *cos-table* nil)
(defparameter *sin-table* nil)

(defmacro with-fixed-base (size &body body)
  "Makes FFT faster when the SIZE of target vectors is fixed in BODY. This macro
computes and holds the roots of unity for SIZE, which DFT! and INVERSE-DFT!
called in BODY automatically detects; they will signal an error when they
receive a vector of different size."
  (let ((s (gensym)))
    `(let ((,s ,size))
       (multiple-value-bind (*cos-table* *sin-table*) (%make-trifunc-table ,s)
         ,@body))))

(defun %dft-fixed-base! (f)
  (declare #.OPT
           ((simple-array fft-float (*)) f))
  (prog1 f
    (let* ((n (length f))
           (cos-table *cos-table*)
           (sin-table *sin-table*)
           (factor n))
      (declare ((integer 0 #.most-positive-fixnum) factor)
               ((simple-array fft-float (*)) cos-table sin-table))
      (assert (power2-p n))
      (assert (= (ash n -2) (length cos-table)))
      ;; bit-reverse ordering
      (let ((i 0))
        (declare ((integer 0 #.most-positive-fixnum) i))
        (loop for j from 1 below (- n 1)
              do (loop for k of-type (integer 0 #.most-positive-fixnum)
                          = (ash n -1) then (ash k -1)
                       while (> k (setq i (logxor i k))))
                 (when (< j i)
                   (rotatef (aref f i) (aref f j)))))
      (do* ((mh 1 m)
            (m (ash mh 1) (ash mh 1)))
           ((> m n))
        (declare ((integer 0 #.most-positive-fixnum) mh m))
        (let ((mq (ash mh -1)))
          (setq factor (ash factor -1))
          (do ((jr 0 (+ jr m)))
              ((>= jr n))
            (declare ((integer 0 #.most-positive-fixnum) jr))
            (let ((xreal (aref f (+ jr mh))))
              (setf (aref f (+ jr mh)) (- (aref f jr) xreal))
              (incf (aref f jr) xreal)))
          (do ((i 1 (+ i 1))
               (table-index factor (+ table-index factor)))
              ((>= i mq))
            (declare ((integer 0 #.most-positive-fixnum) i table-index))
            (let* ((wreal (aref cos-table table-index))
                   (wimag (- (aref sin-table table-index))))
              (do ((j 0 (+ j m)))
                  ((>= j n))
                (let* ((j+mh (+ j mh))
                       (j+m-i (- (+ j m) i))
                       (xreal (+ (* wreal (aref f (+ j+mh i)))
                                 (* wimag (aref f j+m-i))))
                       (ximag (- (* wreal (aref f j+m-i))
                                 (* wimag (aref f (+ j+mh i))))))
                  (declare ((integer 0 #.most-positive-fixnum) j+mh j+m-i))
                  (setf (aref f (+ j+mh i))
                        (+ (- (aref f (- j+mh i))) ximag))
                  (setf (aref f j+m-i)
                        (+ (aref f (- j+mh i)) ximag))
                  (setf (aref f (- j+mh i))
                        (+ (aref f (+ j i)) (- xreal)))
                  (incf (aref f (+ j i)) xreal))))))))))

(defun %inverse-dft-fixed-base! (f)
  (declare #.OPT
           ((simple-array fft-float (*)) f))
  (prog1 f
    (let* ((n (length f))
           (cos-table *cos-table*)
           (sin-table *sin-table*)
           (factor 1))
      (declare ((integer 0 #.most-positive-fixnum) factor)
               ((simple-array fft-float (*)) cos-table sin-table))
      (assert (power2-p n))
      (assert (= (ash n -2) (length cos-table)))
      (setf (aref f 0)
            (/ (aref f 0) 2))
      (setf (aref f (ash n -1))
            (/ (aref f (ash n -1)) 2))
      (do* ((m n mh)
            (mh (ash m -1) (ash m -1)))
           ((zerop mh))
        (declare ((integer 0 #.most-positive-fixnum) m mh))
        (let ((mq (ash mh -1)))
          (do ((jr 0 (+ jr m)))
              ((>= jr n))
            (declare ((integer 0 #.most-positive-fixnum) jr))
            (let ((xreal (- (aref f jr) (aref f (+ jr mh)))))
              (incf (aref f jr) (aref f (+ jr mh)))
              (setf (aref f (+ jr mh)) xreal)))
          (do ((i 1 (+ i 1))
               (table-index factor (+ factor table-index)))
              ((>= i mq))
            (declare ((integer 0 #.most-positive-fixnum) i table-index))
            (let* ((wreal (aref cos-table table-index))
                   (wimag (aref sin-table table-index)))
              (do ((j 0 (+ j m)))
                  ((>= j n))
                (let* ((j+mh (+ j mh))
                       (j+m-i (- (+ j m) i))
                       (xreal (- (aref f (+ j i)) (aref f (- j+mh i))))
                       (ximag (+ (aref f j+m-i) (aref f (+ j+mh i)))))
                  (declare ((integer 0 #.most-positive-fixnum) j+mh j+m-i))
                  (incf (aref f (+ j i)) (aref f (- j+mh i)))
                  (setf (aref f (- j+mh i))
                        (- (aref f j+m-i) (aref f (+ j+mh i))))
                  (setf (aref f (+ j+mh i))
                        (+ (* wreal xreal) (* wimag ximag)))
                  (setf (aref f j+m-i)
                        (- (* wreal ximag) (* wimag xreal))))))))
        (setq factor (ash factor 1)))
      ;; bit-reverse ordering
      (let ((i 0))
        (declare ((integer 0 #.most-positive-fixnum) i))
        (loop for j from 1 below (- n 1)
              do (loop for k of-type (integer 0 #.most-positive-fixnum)
                          = (ash n -1) then (ash k -1)
                       while (> k (setq i (logxor i k))))
                 (when (< j i)
                   (rotatef (aref f i) (aref f j))))))))

(declaim (inline dft!))
(defun dft! (f)
  (declare ((simple-array fft-float (*)) f))
  (if (zerop (length f))
      f
      (%dft-fixed-base! f)))

(declaim (inline inverse-dft!))
(defun inverse-dft! (f)
  (declare ((simple-array fft-float (*)) f))
  (prog1 f
    (let ((n (length f)))
      (unless (zerop n)
        (let ((factor (* 2 (/ (coerce n 'fft-float)))))
          (%inverse-dft-fixed-base! f)
          (dotimes (i n)
            (setf (aref f i) (* (aref f i) factor))))))))

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

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

;; Body
(defconstant +dp-size+ (ash 1 18))

(defun main ()
  (declare #.OPT)
  (let* ((k (read))
         (dp (make-array +dp-size+ :element-type 'fft-float :initial-element 0f0))
         (multiplier (make-array +dp-size+ :element-type 'fft-float :initial-element 0f0)))
    (declare ((integer 0 100000) k)
             ((simple-array fft-float (#.+dp-size+)) dp multiplier))
    (loop for i = 1 then (rem (* i 10) k)
          while (= 0f0 (aref dp i))
          do (setf (aref dp i) 1f0
                   (aref multiplier i) 1f0))
    (with-fixed-base +dp-size+
      (dft! multiplier)
      (loop for i from 1 to 45
            do (when (= 1f0 (aref dp 0))
                 (println i)
                 (return-from main))
               (when (= 44 i)
                 (println 45)
                 (return-from main))
               (dft! dp)
               (setf (aref dp 0)
                     (* (aref dp 0) (aref multiplier 0)))
               (setf (aref dp (ash +dp-size+ -1))
                     (* (aref dp (ash +dp-size+ -1)) (aref multiplier (ash +dp-size+ -1))))
               (loop for i from 1 below (ash +dp-size+ -1)
                     for value1 = (- (* (aref dp i) (aref multiplier i))
                                     (* (aref dp (- +dp-size+ i)) (aref multiplier (- +dp-size+ i))))
                     for value2 = (+ (* (aref dp i) (aref multiplier (- +dp-size+ i)))
                                     (* (aref dp (- +dp-size+ i)) (aref multiplier i)))
                     do (setf (aref dp i) value1
                              (aref dp (- +dp-size+ i)) value2))
               (inverse-dft! dp)
               (dotimes (i k)
                 (if (or (> (aref dp i) 0.5f0)
                         (> (aref dp (+ i k)) 0.5f0))
                     (setf (aref dp i) 1f0)
                     (setf (aref dp i) 0f0))
                 (setf (aref dp (+ i k)) 0f0))
               (loop for i from (* 2 k) below +dp-size+
                     do (setf (aref dp i) 0f0))))))

#-swank(main)

Score : 700 points

Problem Statement

Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Constraints

2 \leq K \leq 10^5

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Sample Input 1

6

Sample Output 1

3

12=6×2 yields the smallest sum.

Sample Input 2

41

Sample Output 2

5

11111=41×271 yields the smallest sum.

Sample Input 3

79992

Sample Output 3

36


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

;; BEGIN_INSERTED_CONTENTS
;; -*- coding:utf-8 -*-
(defstruct (queue (:constructor make-queue
                    (&optional list &aux (tail (last list)))))
  (list nil :type list)
  (tail nil :type (or null (cons t null))))

(declaim (inline enqueue))
(defun enqueue (obj queue)
  (symbol-macrolet ((list (queue-list queue))
                    (tail (queue-tail queue)))
    (if (null list)
        (setf tail (list obj)
              list tail)
        (setf (cdr tail) (list obj)
              tail (cdr tail))))
  queue)

(declaim (inline dequeue))
(defun dequeue (queue)
  (pop (queue-list queue)))

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

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

(defconstant +mod+ 1000000007)

;; Body
(defun main ()
  (declare #.OPT)
  (sb-int:with-progressive-timeout (remaining-time :seconds 1.92)
    (let* ((k (read))
           (queue (make-queue))
           (power10-table (make-array k :element-type 'bit :initial-element 0))
           (dist-table (make-array k :element-type 'uint8 :initial-element #xff)))
      (declare (uint32 k))
      (loop for x = 1 then (mod (* x 10) k)
            until (= 1 (aref power10-table x))
            do (setf (aref power10-table x) 1
                     (aref dist-table x) 1)
               (enqueue x queue)
               (when (zerop x)
                 (println 1)
                 (return-from main)))
      (let ((delta-vec (make-array (count 1 power10-table) :element-type 'uint32))
            (index 0)
            (counter 0))
        (declare (uint32 counter))
        (dotimes (x k)
          (when (= 1 (aref power10-table x))
            (setf (aref delta-vec index) x)
            (incf index)))
        (loop for x of-type uint32 = (dequeue queue)
              do (sb-int:dovector (delta delta-vec)
                   (incf counter)
                   (let ((dest (mod (+ delta x) k)))
                     (when (zerop dest)
                       (println (+ 1 (aref dist-table x)))
                       (return-from main))
                     (when (= #xff (aref dist-table dest))
                       (setf (aref dist-table dest)
                             (+ 1 (aref dist-table x)))
                       (enqueue dest queue))))
                 (when (>= counter 100000)
                   (setq counter 0)
                   (when (zerop (remaining-time))
                     (println 3)
                     (return-from main))))))))

#-swank(main)