;; D - Friend Suggestions

(defun solve (n m k ab cd)
  (let ((adj  (make-array n :initial-element nil))
        (conn (make-array n :initial-element nil))
        (nblock (make-array n :initial-element 0)))
    ; 連結リスト
    (loop for (a . b) in ab
      do (setf (aref adj (1- a)) (cons (1- b) (aref adj (1- a))))
         (setf (aref adj (1- b)) (cons (1- a) (aref adj (1- b)))))
    ; 連結成分
    (loop for a below n
      unless (aref conn a)
        do (find-connected-component a conn adj))
    ; 同じ連結成分内のブロック関係の数
    (loop for (c . d) in cd
      when (gethash (1- c) (cdr (aref conn (1- d)))) ; 同じ連結成分
        do (incf (aref nblock (1- c)))
           (incf (aref nblock (1- d))))
    ; 友達候補 = 連結成分 - 自分 - 友達関係 - ブロック関係
    (loop for a below n
      collect (- (car (aref conn a)) 1 (length (aref adj a))
                 (aref nblock a)))))

(defun find-connected-component (a conn adj)
  (setf (aref conn a) (cons 0 (make-hash-table)))
  (labels ((dfs (queue)
             (when queue
               (let ((x    (car queue))
                     (rest (cdr queue)))
                 (unless (gethash x (cdr (aref conn a)))
                   (setf (gethash x (cdr (aref conn a))) t)
                   (incf (car (aref conn a)))
                   (setf (aref conn x) (aref conn a))
                   (setf rest (append (aref adj x) rest)))
                 (dfs rest)))))
    (dfs (list a))))

(defun main ()
  (let* ((n (read))
         (m (read))
         (k (read))
         (ab (loop repeat m collect (cons (read) (read))))
         (cd (loop repeat k collect (cons (read) (read)))))
    (format t "~{~a~^ ~}~%" (solve n m k ab cd))))

(main)

Score : 400 points

Problem Statement

An SNS has N users - User 1, User 2, \cdots, User N.

Between these N users, there are some relationships - M friendships and K blockships.

For each i = 1, 2, \cdots, M, there is a bidirectional friendship between User A_i and User B_i.

For each i = 1, 2, \cdots, K, there is a bidirectional blockship between User C_i and User D_i.

We define User a to be a friend candidate for User b when all of the following four conditions are satisfied:

a \neq b.

There is not a friendship between User a and User b.

There is not a blockship between User a and User b.

There exists a sequence c_0, c_1, c_2, \cdots, c_L consisting of integers between 1 and N (inclusive) such that c_0 = a, c_L = b, and there is a friendship between User c_i and c_{i+1} for each i = 0, 1, \cdots, L - 1.

For each user i = 1, 2, ... N, how many friend candidates does it have?

Constraints

All values in input are integers.

2 ≤ N ≤ 10^5

0 \leq M \leq 10^5

0 \leq K \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

1 \leq C_i, D_i \leq N

C_i \neq D_i

(A_i, B_i) \neq (A_j, B_j) (i \neq j)

(A_i, B_i) \neq (B_j, A_j)

(C_i, D_i) \neq (C_j, D_j) (i \neq j)

(C_i, D_i) \neq (D_j, C_j)

(A_i, B_i) \neq (C_j, D_j)

(A_i, B_i) \neq (D_j, C_j)

Input

Input is given from Standard Input in the following format:

N M K
A_1 B_1
\vdots
A_M B_M
C_1 D_1
\vdots
C_K D_K

Output

Print the answers in order, with space in between.

Sample Input 1

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

Sample Output 1

0 1 0 1

There is a friendship between User 2 and 3, and between 3 and 4. Also, there is no friendship or blockship between User 2 and 4. Thus, User 4 is a friend candidate for User 2.

However, neither User 1 or 3 is a friend candidate for User 2, so User 2 has one friend candidate.

Sample Input 2

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

Sample Output 2

0 0 0 0 0

Everyone is a friend of everyone else and has no friend candidate.

Sample Input 3

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

Sample Output 3

1 3 5 4 3 3 3 3 1 0


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

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

(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 calc (n k xs ys cs)
  (when ))

(defun main ()
  (declare #.OPT
           (inline sort))
  (let* ((n (read))
         (k (read))
         (xs (make-array n :element-type 'double-float))
         (ys (make-array n :element-type 'double-float))
         (cs (make-array n :element-type 'double-float)))
    (declare (uint8 n k))
    (dotimes (i n)
      (setf (aref xs i) (float (read) 1d0)
            (aref ys i) (float (read) 1d0)
            (aref cs i) (float (read) 1d0)))
    (let ((tmp (make-array n :element-type 'double-float)))
      (declare ((simple-array double-float (*)) tmp))
      (labels ((calc (pivot-x pivot-y)
                 (declare (double-float pivot-x pivot-y))
                 (dotimes (i n)
                   (let ((x (aref xs i))
                         (y (aref ys i))
                         (c (aref cs i)))
                     (setf (aref tmp i)
                           (* c (sqrt (+ (expt (- x pivot-x) 2)
                                         (expt (- y pivot-y) 2)))))))
                 (setq tmp (sort tmp #'<))
                 (aref tmp (- k 1)))
               (%%minimize (pivot-x pivot-y rad div)
                 (declare (double-float pivot-x pivot-y rad)
                          (uint32 div))
                 (let ((delta (/ rad div))
                       (res most-positive-double-float))
                   (declare (double-float delta res))
                   (loop for x from (- pivot-x rad) to (+ pivot-x rad) by delta
                         do (loop for y from (- pivot-y rad) to (+ pivot-y rad) by delta
                                  do (minf res (calc x y))))
                   res))
               (%minimize (x1 y1 x2 y2 rate div)
                 (declare (double-float x1 y1 x2 y2 rate))
                 (let* ((xmid (* 0.5d0 (+ x1 x2)))
                        (ymid (* 0.5d0 (+ y1 y2)))
                        (delta (* 0.5d0 (max (abs (* 0.5d0 (- xmid x1)))
                                             (abs (* 0.5d0 (- ymid y1)))))))
                   (let* ((min00 (%%minimize (* 0.5d0 (+ x1 xmid))
                                             (* 0.5d0 (+ y1 ymid))
                                             (* 1.5d0 delta) div))
                          (min01 (%%minimize (* 0.5d0 (+ xmid x2))
                                             (* 0.5d0 (+ y1 ymid))
                                             (* 1.5d0 delta) div))
                          (min10 (%%minimize (* 0.5d0 (+ x1 xmid))
                                             (* 0.5d0 (+ ymid y2))
                                             (* 1.5d0 delta) div))
                          (min11 (%%minimize (* 0.5d0 (+ xmid x2))
                                             (* 0.5d0 (+ ymid y2))
                                             (* 1.5d0 delta) div))
                          (min (min min00 min01 min10 min11))
                          (d (* rate delta)))
                     (cond ((< delta 1d-10) min)
                           ((= min min00) (%minimize (- x1 d) (- y1 d) (+ xmid d) (+ ymid d) rate div))
                           ((= min min01) (%minimize (- xmid d) (- y1 d) (+ x2 d) (+ ymid d) rate div))
                           ((= min min10) (%minimize (- x1 d) (- ymid d) (+ xmid d) (+ y2 d) rate div))
                           ((= min min11) (%minimize (- xmid d) (- ymid d) (+ x2 d) (+ y2 d) rate div))
                           (t (error "Huh?")))))))
        (println (min (%minimize -1101.1d0 -1050.9d0 1040.3d0 1031.6d0 0.75d0 10)
                      (%minimize -1101.1d0 -1050.9d0 1040.3d0 1031.6d0 0.5d0 10)
                      (%minimize -1101.1d0 -1050.9d0 1040.3d0 1031.6d0 0.25d0 10)
                      (%minimize -1101.1d0 -1050.9d0 1040.3d0 1031.6d0 0.35d0 10)
                      (%minimize -1101.1d0 -1050.9d0 1040.3d0 1031.6d0 0.1d0 10)
                      (%minimize -1101.1d0 -1050.9d0 1040.3d0 1031.6d0 0.6d0 10)
                      (%minimize -1101.1d0 -1050.9d0 1040.3d0 1031.6d0 0.8d0 10)))))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4 3
-1 0 3
0 0 3
1 0 2
1 1 40
"
    "2.4
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "10 5
-879 981 26
890 -406 81
512 859 97
362 -955 25
128 553 17
-885 763 2
449 310 57
-656 -204 11
-270 76 40
184 170 16
"
    "7411.2252
")))

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

Score : 600 points

Problem Statement

Takahashi wants to grill N pieces of meat on a grilling net, which can be seen as a two-dimensional plane. The coordinates of the i-th piece of meat are \left(x_i, y_i\right), and its hardness is c_i.

Takahashi can use one heat source to grill the meat. If he puts the heat source at coordinates \left(X, Y\right), where X and Y are real numbers, the i-th piece of meat will be ready to eat in c_i \times \sqrt{\left(X - x_i\right)^2 + \left(Y-y_i\right)^2} seconds.

Takahashi wants to eat K pieces of meat. Find the time required to have K or more pieces of meat ready if he put the heat source to minimize this time.

Constraints

All values in input are integers.

1 \leq N \leq 60

1 \leq K \leq N

-1000 \leq x_i , y_i \leq 1000

\left(x_i, y_i\right) \neq \left(x_j, y_j\right) \left(i \neq j \right)

1 \leq c_i \leq 100

Input

Input is given from Standard Input in the following format:

N K
x_1 y_1 c_1
\vdots
x_N y_N c_N

Output

Print the answer.

It will be considered correct if its absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

4 3
-1 0 3
0 0 3
1 0 2
1 1 40

Sample Output 1

2.4

If we put the heat source at \left(-0.2, 0\right), the 1-st, 2-nd, and 3-rd pieces of meat will be ready to eat within 2.4 seconds. This is the optimal place to put the heat source.

Sample Input 2

10 5
-879 981 26
890 -406 81
512 859 97
362 -955 25
128 553 17
-885 763 2
449 310 57
-656 -204 11
-270 76 40
184 170 16

Sample Output 2

7411.2252

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.


;; A - Beginner

(let ((n (read))  ; 参加回数
      (r (read))) ; 表示レーティング
  ; r = x - 100 × (10 - n) if n < 10 else x
  (princ (if (< n 10) (+ r (* 100 (- 10 n))) r)))

Score : 100 points

Problem Statement

Takahashi is a member of a programming competition site, ButCoder.

Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating.

The Displayed Rating of a member is equal to their Inner Rating if the member has participated in 10 or more contests. Otherwise, the Displayed Rating will be their Inner Rating minus 100 \times (10 - K) when the member has participated in K contests.

Takahashi has participated in N contests, and his Displayed Rating is R. Find his Inner Rating.

Constraints

All values in input are integers.

1 \leq N \leq 100

0 \leq R \leq 4111

Input

Input is given from Standard Input in the following format:

N R

Output

Print his Inner Rating.

Sample Input 1

2 2919

Sample Output 1

3719

Takahashi has participated in 2 contests, which is less than 10, so his Displayed Rating is his Inner Rating minus 100 \times (10 - 2) = 800.

Thus, Takahashi's Inner Rating is 2919 + 800 = 3719.

Sample Input 2

22 3051

Sample Output 2

3051


;; B - Digits

(let ((n (read))
      (k (read)))
  ; nをk進数で表したときの桁数
  (princ (1+ (floor (log n k)))))

Score : 200 points

Problem Statement

Given is an integer N. Find the number of digits that N has in base K.

Notes

For information on base-K representation, see Positional notation - Wikipedia.

Constraints

All values in input are integers.

1 \leq N \leq 10^9

2 \leq K \leq 10

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of digits that N has in base K.

Sample Input 1

11 2

Sample Output 1

4

In binary, 11 is represented as 1011.

Sample Input 2

1010101 10

Sample Output 2

7

Sample Input 3

314159265 3

Sample Output 3

18


;; C - Rally

(defun solve (xs)
  "min(sum((x - p) ** 2 for x in xs) for p in range(1, 101))"
  (loop for p from 1 to 100
    minimize (reduce #'+ (mapcar #'(lambda (x) (expt (- x p) 2)) xs))))

(let* ((n  (read))
       (xs (loop repeat n collect (read))))
  (princ (solve xs)))

Score : 300 points

Problem Statement

There are N people living on a number line.

The i-th person lives at coordinate X_i.

You are going to hold a meeting that all N people have to attend.

The meeting can be held at any integer coordinate. If you choose to hold the meeting at coordinate P, the i-th person will spend (X_i - P)^2 points of stamina to attend the meeting.

Find the minimum total points of stamina the N people have to spend.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq X_i \leq 100

Input

Input is given from Standard Input in the following format:

N
X_1 X_2 ... X_N

Output

Print the minimum total stamina the N people have to spend.

Sample Input 1

2
1 4

Sample Output 1

5

Assume the meeting is held at coordinate 2. In this case, the first person will spend (1 - 2)^2 points of stamina, and the second person will spend (4 - 2)^2 = 4 points of stamina, for a total of 5 points of stamina. This is the minimum total stamina that the 2 people have to spend.

Note that you can hold the meeting only at an integer coordinate.

Sample Input 2

7
14 14 2 13 56 2 37

Sample Output 2

2354


(let ((p 1000000007))
  (defun mod+ (a b)
    (mod (+ a b) p))
  (defun mod* (a b)
    (mod (* a b) p))
  (defun mod_expt (a z)
    (loop :with ans := 1
          :with pow := a
          :while (> z 0)
          :do (multiple-value-bind (x y) (floor z 2)
                (setf z x)
                (if (= y 1) (setf ans (mod* ans pow)))
                (setf pow (mod* pow pow)))
          :finally (return ans)))
  (defun mod_inv (a)
    (mod_expt a (- p 2))))

(let ((n (read))
      (a (read))
      (b (read))
      (ac 1)
      (bc 1)
      (ans 0))
  (loop :with x := 1
        :for i :from 1 :to (max a b)
        :do (setf x (mod* x (mod* (mod_inv i) (- n i -1))))
        :if (= a i)
        :do (setf ac x)
        :if (= b i)
        :do (setf bc x))
  (setf ans (mod+ ans (mod_expt 2 n)))
  (setf ans (mod+ ans (- 1)))
  (setf ans (mod+ ans (- ac)))
  (setf ans (mod+ ans (- bc)))
  (format t "~A~%" ans))

Score : 400 points

Problem Statement

Akari has n kinds of flowers, one of each kind.

She is going to choose one or more of these flowers to make a bouquet.

However, she hates two numbers a and b, so the number of flowers in the bouquet cannot be a or b.

How many different bouquets are there that Akari can make?

Find the count modulo (10^9 + 7).

Here, two bouquets are considered different when there is a flower that is used in one of the bouquets but not in the other bouquet.

Constraints

All values in input are integers.

2 \leq n \leq 10^9

1 \leq a < b \leq \textrm{min}(n, 2 \times 10^5)

Input

Input is given from Standard Input in the following format:

n a b

Output

Print the number of bouquets that Akari can make, modulo (10^9 + 7). (If there are no such bouquets, print 0.)

Sample Input 1

4 1 3

Sample Output 1

7

In this case, Akari can choose 2 or 4 flowers to make the bouquet.

There are 6 ways to choose 2 out of the 4 flowers, and 1 way to choose 4, so there are a total of 7 different bouquets that Akari can make.

Sample Input 2

1000000000 141421 173205

Sample Output 2

34076506

Print the count modulo (10^9 + 7).


;; E - Roaming

(defparameter *modulus* (+ (expt 10 9) 7))

(defun solve (n k)
  "sum((n人をn-m部屋に空き部屋なしで分ける) * (m個の空き部屋の配置)
       for m in range(0, min(k, n-1) + 1))"
  ; = sum(choose(n-1, n-m-1) * choose(n, m))
  ; = sum(choose(n-1, m) * choose(n, m))
  ; = sum((n-m) * choose(n, m)**2)/n
  ; choose(n, m+1) = choose(n, m) * (n-m)/(m+1)
  (mod/ (loop for m from 0 below (min n (1+ k))
              and choose-n-m = 1
                  then (mod/ (mod* choose-n-m (- n m)) (1+ m))
          sum (mod* (- n m) choose-n-m choose-n-m))
        n))

(defun main ()
  (let ((n (read))
        (k (read)))
    (princ (solve n k))))

;; modulo addition/product/division

(defun mod+ (&rest rest)
  (mod (apply #'+ rest) *modulus*))

(defun mod* (&rest rest)
  (mod (apply #'* rest) *modulus*))

(defun mod/ (num &rest denom)
  (apply #'mod* (cons num (mapcar #'mod-inverse denom))))

(defun bit-sequence (v)
  "(bit-sequence 13) => (1 1 0 1)"
  (nreverse
    (loop for x = v then (ash x -1) while (plusp x)
          collect (logand x 1))))

(let ((modulus-2-bits (bit-sequence (- *modulus* 2))))
  ; Mが素数のとき，a^(M-2) ≡ a^(-1) mod M (フェルマーの小定理より)
  (defun mod-inverse (a)
    (loop for b in modulus-2-bits
          for e = a then (mod* e e (if (zerop b) 1 a))
          finally (return e))))

(main)

Score : 500 points

Problem Statement

There is a building with n rooms, numbered 1 to n.

We can move from any room to any other room in the building.

Let us call the following event a move: a person in some room i goes to another room j~ (i \neq j).

Initially, there was one person in each room in the building.

After that, we know that there were exactly k moves happened up to now.

We are interested in the number of people in each of the n rooms now. How many combinations of numbers of people in the n rooms are possible?

Find the count modulo (10^9 + 7).

Constraints

All values in input are integers.

3 \leq n \leq 2 \times 10^5

2 \leq k \leq 10^9

Input

Input is given from Standard Input in the following format:

n k

Output

Print the number of possible combinations of numbers of people in the n rooms now, modulo (10^9 + 7).

Sample Input 1

3 2

Sample Output 1

10

Let c_1, c_2, and c_3 be the number of people in Room 1, 2, and 3 now, respectively. There are 10 possible combination of (c_1, c_2, c_3):

(0, 0, 3)

(0, 1, 2)

(0, 2, 1)

(0, 3, 0)

(1, 0, 2)

(1, 1, 1)

(1, 2, 0)

(2, 0, 1)

(2, 1, 0)

(3, 0, 0)

For example, (c_1, c_2, c_3) will be (0, 1, 2) if the person in Room 1 goes to Room 2 and then one of the persons in Room 2 goes to Room 3.

Sample Input 2

200000 1000000000

Sample Output 2

607923868

Print the count modulo (10^9 + 7).

Sample Input 3

15 6

Sample Output 3

22583772


#-swank
(unless (member :child-sbcl *features*)
  (quit
    :unix-status
    (process-exit-code
      (run-program *runtime-pathname*
                   `("--control-stack-size" "128MB"
                     "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                     "--eval" "(push :child-sbcl *features*)"
                     "--script" ,(namestring *load-pathname*))
                   :output t :error t :input t))))

(defparameter *hash-memo* (make-hash-table :test #'equal))

(defmacro dp (&body func)
  `(let* ((f (quote func))
          (num (gethash f *hash-memo*)))
     (if num
       num
       (setf (gethash f *hash-memo*) ,func))))

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

(defun count-zeros (a m)
  (loop for i in a sum (if (zerop (car i)) (cdr i) 0)))

(defun culc-sum (a init)
  (+ init (loop for i in a sum (* (car i) (cdr i)))))
(labels ((count-zeros (a m)
                      (loop for i in a sum (if (zerop (car i)) (cdr i) 0)))
         (culc-sum (a init)
                   (+ init (loop for i in a sum (* (car i) (cdr i))))))

  (let* ((d (read))
         (querys (read))
         (a (loop repeat d collect (read))))
    (dotimes (query-cnt querys)
      (let* ((n (1- (read)))
             (x (read))
             (m (read))
             (ca (loop for i below d
                       for j in a
                       collect
                       (cons (mod j m) (floor (- (+ n d) i 1) d)))))
        (format t "~a~%" (- n (count-zeros ca m) (floor (culc-sum ca (mod x m)) m)))))))

Score : 600 points

Problem Statement

We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.

Process the following q queries in order:

The i-th query contains three integers n_i, x_i, and m_i.
Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray}
Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).

Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).

Constraints

All values in input are integers.

1 \leq k, q \leq 5000

0 \leq d_i \leq 10^9

2 \leq n_i \leq 10^9

0 \leq x_i \leq 10^9

2 \leq m_i \leq 10^9

Input

Input is given from Standard Input in the following format:

k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q

Output

Print q lines.

The i-th line should contain the response to the i-th query.

Sample Input 1

3 1
3 1 4
5 3 2

Sample Output 1

1

For the first query, the sequence {a_j} will be 3,6,7,11,14.

(a_0~\textrm{mod}~2) > (a_1~\textrm{mod}~2)

(a_1~\textrm{mod}~2) < (a_2~\textrm{mod}~2)

(a_2~\textrm{mod}~2) = (a_3~\textrm{mod}~2)

(a_3~\textrm{mod}~2) > (a_4~\textrm{mod}~2)

Thus, the response to this query should be 1.

Sample Input 2

7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12

Sample Output 2

224489796
214285714
559523809


(let ((a (read))
      (b (read))
      (c (read)))
  (if (or (and (= a b) (/= b c))
          (and (= b c) (/= c a))
          (and (= c a) (/= a b)))
      (format t "Yes~%")
      (format t "No~%")))

Score: 100 points

Problem Statement

A triple of numbers is said to be poor when two of those numbers are equal but the other number is different from those two numbers.

You will be given three integers A, B, and C. If this triple is poor, print Yes; otherwise, print No.

Constraints

A, B, and C are all integers between 1 and 9 (inclusive).

Input

Input is given from Standard Input in the following format:

A B C

Output

If the given triple is poor, print Yes; otherwise, print No.

Sample Input 1

5 7 5

Sample Output 1

Yes

A and C are equal, but B is different from those two numbers, so this triple is poor.

Sample Input 2

4 4 4

Sample Output 2

No

A, B, and C are all equal, so this triple is not poor.

Sample Input 3

4 9 6

Sample Output 3

No

Sample Input 4

3 3 4

Sample Output 4

Yes


(let ((result (length (remove-duplicates (list (read) (read) (read)) :test #'=))))
    (princ (if (or (= result 1) (= result 2))
               "Yes"
               "No")))


(defun main ()
  (let ((result (length (remove-duplicates (list (read) (read) (read)) :test #'=))))
    (princ (if (or (= result 1) (= result 2))
               "Yes"
               "No"))))


(defun solve (n list)
  (loop for a in list
        if (and (evenp a)
                (not (or (= 0 (mod a 3))
                         (= 0 (mod a 5)))))
        do (return "DENIED")
        finally (return "APPROVED")))

#-swank
(let* ((n (read))
       (list (loop repeat n collect (read))))
  (format t "~A~%" (solve n list)))

Score: 200 points

Problem Statement

You are an immigration officer in the Kingdom of AtCoder. The document carried by an immigrant has some number of integers written on it, and you need to check whether they meet certain criteria.

According to the regulation, the immigrant should be allowed entry to the kingdom if and only if the following condition is satisfied:

All even numbers written on the document are divisible by 3 or 5.

If the immigrant should be allowed entry according to the regulation, output APPROVED; otherwise, print DENIED.

Notes

The condition in the statement can be rephrased as "If x is an even number written on the document, x is divisible by 3 or 5".
Here "if" and "or" are logical terms.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq A_i \leq 1000

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

If the immigrant should be allowed entry according to the regulation, print APPROVED; otherwise, print DENIED.

Sample Input 1

5
6 7 9 10 31

Sample Output 1

APPROVED

The even numbers written on the document are 6 and 10.

All of them are divisible by 3 or 5, so the immigrant should be allowed entry.

Sample Input 2

3
28 27 24

Sample Output 2

DENIED

28 violates the condition, so the immigrant should not be allowed entry.


(let* ((n (read))
    (*hash* (make-hash-table :test 'equal :size n))
    (a 1)
    (ans (make-array n :fill-pointer 0 :adjustable t)))
    (loop for i below n do
        (let ((s (read)))
            (if (gethash s *hash*)
                (progn
                (incf (gethash s *hash*))
                    (if (< a (gethash s *hash*))
                        (incf a)
                    )
                )
                (setf (gethash s *hash*) 1)
            )
        )
    )
    (let ((i 0))
    (loop for key being each hash-key of *hash*
        using (hash-value value) when (= value a)
        do
        (progn
            (setf (aref ans i) key)
            (incf i)
        )
    )
    (setf ans (sort ans #'string<))

    (loop for j below i do
        (format t "~(~A~)~%" (aref ans j))
    )
    )
)

Score: 300 points

Problem Statement

We have N voting papers. The i-th vote (1 \leq i \leq N) has the string S_i written on it.

Print all strings that are written on the most number of votes, in lexicographical order.

Constraints

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

S_i (1 \leq i \leq N) are strings consisting of lowercase English letters.

The length of S_i (1 \leq i \leq N) is between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

Print all strings in question in lexicographical order.

Sample Input 1

7
beat
vet
beet
bed
vet
bet
beet

Sample Output 1

beet
vet

beet and vet are written on two sheets each, while beat, bed, and bet are written on one vote each. Thus, we should print the strings beet and vet.

Sample Input 2

8
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo

Sample Output 2

buffalo

Sample Input 3

7
bass
bass
kick
kick
bass
kick
kick

Sample Output 3

kick

Sample Input 4

4
ushi
tapu
nichia
kun

Sample Output 4

kun
nichia
tapu
ushi


(defparameter *hash* (make-hash-table))
(let ((n (read))
    (a 0)
    (ans '()))
    (loop for i below n do
        (let ((s (read)))
            (if (gethash s *hash*)
                (incf (gethash s *hash*))
                (setf (gethash s *hash*) 1)
            )
            ;;一番多い文字列の個数
            (if (< a (gethash s *hash*))
                (setq a (gethash s *hash*))
            )
        )
    )
    (maphash (lambda (key value) (if (= value a) (push key ans))) *hash*)
    (setq ans (sort ans #'string<))

    (loop for i below (length ans) do
        (format t "~(~A~)~%" (nth i ans))
    )
)


(defparameter *hash* (make-hash-table))
(let ((n (read))
    (a 0)
    (ans '()))
    (loop for i below n do
        (let ((s (read)))
            (if (gethash s *hash*)
                (incf (gethash s *hash*))
                (setf (gethash s *hash*) 1)
            )
            ;;一番多い文字列の個数
            (if (< a (gethash s *hash*))
                (setq a (gethash s *hash*))
            )
        )
    )
    (setq ans (loop for key being each hash-key of *hash*
        using (hash-value value) when (= value a)collect key
    ))
    (setf ans (sort ans #'string<))

    (loop for i below (length ans) do
        (format t "~(~A~)~%" (nth i ans))
    )
)


(let* ((n (read))
       (m (make-hash-table :test 'equal :size n))
       (s (make-array (list n))))
  (loop :for i :from 0 :to (1- n)
        :do (let ((x (read-line)))
              (if (gethash x m)
                  (incf (gethash x m))
                  (setf (gethash x m) 1))
              (setf (aref s i) (cons x (gethash x m)))))
  (setf s (sort s (lambda (a b) (or (> (cdr a) (cdr b))
                                    (and (= (cdr a) (cdr b))
                                         (string< (car a) (car b)))))))
  (let ((f (cdr (aref s 0))))
    (loop :for x :across s
          :when (= (cdr x) f)
          :do (format t "~A~%" (car x)))))


(defun record (str ht)
  (let ((h (gethash str ht)))
    (setf (gethash str ht) (if h (1+ h) 1))))

(defun read-record(N ht)
  (if (<= N 0) ()
    (progn
      (record (read) ht)
      (read-record (1- N) ht))
    ))

(defun ht2alist (table)
  (let ((alist nil))
    (maphash (lambda (k v)
	       (push (cons k v) alist))
	     table)
    alist))

(let ((ht (make-hash-table :test #'equal)))
  (read-record (read) ht)
  (setq alist (sort (ht2alist ht) #'> :key #'cdr))
  (setq alist (remove-if (lambda (x) (< (cdr x) (cdr (car alist)))) alist))
  (setq alist (sort (mapcar 'car alist) #'string<))

  (format t "~{~A~^~%~}" (mapcar 'string-downcase alist)))


(defun collector (function lst); listの各要素を数えるコレクタ 10^7くらいまで
  (if lst
      (let* ((ans '())
             (mem (cons (car lst) 1)))
        (mapcar (lambda (k)
                  (if (funcall function k (car mem))
                      (incf (cdr mem))
                      (progn (push mem ans)
                             (setf mem (cons k 1))))) (cdr lst))
        (push mem ans)
        ans)
      '()))
(let* ((n (read))
       (lst (sort (loop :repeat n :collect (read-line)) #'string>))
       (ll (collector #'string= lst))
       (mx (reduce #'max (mapcar #'cdr ll)))
       (lk (remove-if-not (lambda (k) (= mx (cdr k))) ll)))
  (loop :for k :in lk :do(format t "~A~%" (car k))))


(defun app ()
    (let ((read_s (read))
        (read_t (read)))
    (defparameter *hash* (make-hash-table))
    (setf (gethash read_s *hash*) (read))
    (setf (gethash read_t *hash*) (read))
    (decf (gethash (read) *hash*))
    (format t "~D ~D~%" (gethash read_s *hash*) (gethash read_t *hash*)))
)
(app)

Score : 100 points

Problem Statement

We have A balls with the string S written on each of them and B balls with the string T written on each of them.

From these balls, Takahashi chooses one with the string U written on it and throws it away.

Find the number of balls with the string S and balls with the string T that we have now.

Constraints

S, T, and U are strings consisting of lowercase English letters.

The lengths of S and T are each between 1 and 10 (inclusive).

S \not= T

S=U or T=U.

1 \leq A,B \leq 10

A and B are integers.

Input

Input is given from Standard Input in the following format:

S T
A B
U

Output

Print the answer, with space in between.

Sample Input 1

red blue
3 4
red

Sample Output 1

2 4

Takahashi chose a ball with red written on it and threw it away.
Now we have two balls with the string S and four balls with the string T.

Sample Input 2

red blue
5 5
blue

Sample Output 2

5 4

Takahashi chose a ball with blue written on it and threw it away.
Now we have five balls with the string S and four balls with the string T.


(let ((l (read))
      (r (read))
      (l-num (read))
      (r-num (read)))
  (if (string= l (read))
      (decf l-num)
      (decf r-num))
  (format t "~A ~A~%" l-num r-num))


(defun i-miss-you ()
  (let ((s (read-line)))
    (loop :for char :across s
          :do (princ #\x))
    (format t "~%")))

(i-miss-you)

Score : 200 points

Problem Statement

Given is a string S. Replace every character in S with x and print the result.

Constraints

S is a string consisting of lowercase English letters.

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

Input

Input is given from Standard Input in the following format:

S

Output

Replace every character in S with x and print the result.

Sample Input 1

sardine

Sample Output 1

xxxxxxx

Replacing every character in S with x results in xxxxxxx.

Sample Input 2

xxxx

Sample Output 2

xxxx

Sample Input 3

gone

Sample Output 3

xxxx


(defun splitat (c line)
  (labels ((rec (line acc)
				(let ((pos (position-if (lambda(cc) (char= c cc)) line)))
				  (if pos
					  (rec (subseq line (1+ pos)) (cons (subseq line 0 pos) acc))
					(nreverse (cons line acc))))))
	(rec line nil)))
(defun ff(n arr)
  (let ((sorted (sort arr #'<))
        (found nil))
    (dotimes (i (1- n))
      (if (= (elt sorted i) (elt sorted (1+ i)))
        (setq found t)))
    (if found "NO" "YES")))
(defun f(n arr)
  (let* ((sorted (sort arr #'<))
        (arr1 (subseq sorted 1)))
    (if (some #'= sorted arr1) "NO" "YES")))
(compile 'f)
(let* ((n (parse-integer (read-line nil nil)))
       (line1 (mapcar #'parse-integer (splitat #\space (read-line nil nil))))
       (arr (make-array (length line1) :initial-contents line1)))
  (format t "~A~%" (f n arr)))

Score : 300 points

Problem Statement

Given is a sequence of integers A_1, A_2, ..., A_N.
If its elements are pairwise distinct, print YES; otherwise, print NO.

Constraints

2 ≤ N ≤ 200000

1 ≤ A_i ≤ 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N

Output

If the elements of the sequence are pairwise distinct, print YES; otherwise, print NO.

Sample Input 1

5
2 6 1 4 5

Sample Output 1

YES

The elements are pairwise distinct.

Sample Input 2

6
4 1 3 1 6 2

Sample Output 2

NO

The second and fourth elements are identical.

Sample Input 3

2
10000000 10000000

Sample Output 3

NO


(defun solve (K lst)
  (loop for x in (mapcar #'- (nthcdr K lst) lst)
        with y = (loop for x in lst for i below K sum x)
        maximize (incf y x)))

(let ((N (read))
      (K (read)))
     (format t "~F"
             (solve K (loop repeat N
                            collect (/ (1+ (read)) 2))) ))

Score : 400 points

Problem Statement

We have N dice arranged in a line from left to right. The i-th die from the left shows p_i numbers from 1 to p_i with equal probability when thrown.

We will choose K adjacent dice, throw each of them independently, and compute the sum of the numbers shown. Find the maximum possible value of the expected value of this sum.

Constraints

1 ≤ K ≤ N ≤ 200000

1 ≤ p_i ≤ 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
p_1 ... p_N

Output

Print the maximum possible value of the expected value of the sum of the numbers shown.

Your output will be considered correct when its absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

5 3
1 2 2 4 5

Sample Output 1

7.000000000000

When we throw the third, fourth, and fifth dice from the left, the expected value of the sum of the numbers shown is 7. This is the maximum value we can achieve.

Sample Input 2

4 1
6 6 6 6

Sample Output 2

3.500000000000

Regardless of which die we choose, the expected value of the number shown is 3.5.

Sample Input 3

10 4
17 13 13 12 15 20 10 13 17 11

Sample Output 3

32.000000000000


(let* ((n (read))
       (m (read))
       (l (loop :repeat n :collect (read)))
       (k 0)
       (f 0))
  (loop :for j :from 0 :upto (- n m)
        :do(setf k (reduce #'+ (mapcar (lambda (a) (/ (* 0.5 a (1+ a)) a)) (subseq l j (+ j m)))))
        :do(if (< f k)
               (setf f k)))
  (princ f))


Score : 100 points

Problem Statement

Serval is fighting with a monster.

The health of the monster is H.

In one attack, Serval can decrease the monster's health by A.
There is no other way to decrease the monster's health.

Serval wins when the monster's health becomes 0 or below.

Find the number of attacks Serval needs to make before winning.

Constraints

1 \leq H \leq 10^4

1 \leq A \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H A

Output

Print the number of attacks Serval needs to make before winning.

Sample Input 1

10 4

Sample Output 1

3

After one attack, the monster's health will be 6.

After two attacks, the monster's health will be 2.

After three attacks, the monster's health will be -2.

Thus, Serval needs to make three attacks to win.

Sample Input 2

1 10000

Sample Output 2

1

Sample Input 3

10000 1

Sample Output 3

10000


(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* ((h (read))
         (a (read)))
    (println (ceiling h a))))

#-swank (main)

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

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

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

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

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

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

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

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

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


(defun app ()
    (let ((h (read))
        (n (read))
        (a 0))
        (setq a (loop for _ below n sum (read)))
        (if (<= h a)
        (princ "Yes")
        (princ "No"))
    )
)
(app)

Score : 200 points

Problem Statement

Raccoon is fighting with a monster.

The health of the monster is H.

Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i.
There is no other way to decrease the monster's health.

Raccoon wins when the monster's health becomes 0 or below.

If Raccoon can win without using the same move twice or more, print Yes; otherwise, print No.

Constraints

1 \leq H \leq 10^9

1 \leq N \leq 10^5

1 \leq A_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H N
A_1 A_2 ... A_N

Output

If Raccoon can win without using the same move twice or more, print Yes; otherwise, print No.

Sample Input 1

10 3
4 5 6

Sample Output 1

Yes

The monster's health will become 0 or below after, for example, using the second and third moves.

Sample Input 2

20 3
4 5 6

Sample Output 2

No

Sample Input 3

210 5
31 41 59 26 53

Sample Output 3

Yes

Sample Input 4

211 5
31 41 59 26 53

Sample Output 4

No


(if (<= (read)
        (apply #'+ (loop :repeat (read) :collect (read))))
    (princ "Yes")
    (princ "No"))


(defun get-input-array (n)
  (let ((rst (make-array n)))
    (dotimes (i n)
      (setf (aref rst i) (read)))
    rst))

(defun main (h n)
  (let* ((input (get-input-array n))
        (remaining h)
        (rst "No"))
    (loop for i from (- n 1) downto 0
          do (setf remaining (- remaining (aref input i)))
             '(format t  "~A ~A ~A~%" i remaining n)
          if (<= remaining 0) do (progn (setf rst "Yes")
                                   (return))
          )
    rst))

(format t "~A~%" (main (read) (read)))


(defun solve (h n actions)
  (declare (ignore n))
  (<= h (reduce #'+ actions)))

#-swank
(let* ((h (read))
       (n (read))
       (actions (loop repeat n collect (read))))
  (format t "~:[No~;Yes~]~%" (solve h n actions)))


(defun create-data ()
  (let ((n (read))
        (k (read))
        (h))
    (dotimes (i n)
      (push (read) h))
    (sort h #'>)
    (values n k h)))

(defun fennec-vs-monster (n k h)
  (dotimes (i k)
    (pop h)
    (if (null h)
        (return)))
  (loop for i in h
        sum i))

(multiple-value-bind (n k h) (create-data)
  (format t "~D~%" (fennec-vs-monster n k h)))

Score : 300 points

Problem Statement

Fennec is fighting with N monsters.

The health of the i-th monster is H_i.

Fennec can do the following two actions:

Attack: Fennec chooses one monster. That monster's health will decrease by 1.

Special Move: Fennec chooses one monster. That monster's health will become 0.

There is no way other than Attack and Special Move to decrease the monsters' health.

Fennec wins when all the monsters' healths become 0 or below.

Find the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning when she can use Special Move at most K times.

Constraints

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

0 \leq K \leq 2 \times 10^5

1 \leq H_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
H_1 ... H_N

Output

Print the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning.

Sample Input 1

3 1
4 1 5

Sample Output 1

5

By using Special Move on the third monster, and doing Attack four times on the first monster and once on the second monster, Fennec can win with five Attacks.

Sample Input 2

8 9
7 9 3 2 3 8 4 6

Sample Output 2

0

She can use Special Move on all the monsters.

Sample Input 3

3 0
1000000000 1000000000 1000000000

Sample Output 3

3000000000

Watch out for overflow.


(defun get-input-array (n)
  (let ((rst (make-array n)))
    (dotimes (i n)
      (setf (aref rst i) (read)))
    rst))

(defun main (n k)
  (let* ((input (get-input-array n))
        (hi 0))
    (if (=  k 0)
        (setf hi 0)
      (setf hi k))
    (setf input (sort input #'>))
    (loop for i from hi to (- n 1)
          sum (aref input i))))

(format t "~A~%" (main (read) (read)))


(princ (1- (expt 2 (length (format nil "~B" (read))))))

Score : 400 points

Problem Statement

Caracal is fighting with a monster.

The health of the monster is H.

Caracal can attack by choosing one monster. When a monster is attacked, depending on that monster's health, the following happens:

If the monster's health is 1, it drops to 0.

If the monster's health, X, is greater than 1, that monster disappears. Then, two new monsters appear, each with the health of \lfloor X/2 \rfloor.

(\lfloor r \rfloor denotes the greatest integer not exceeding r.)

Caracal wins when the healths of all existing monsters become 0 or below.

Find the minimum number of attacks Caracal needs to make before winning.

Constraints

1 \leq H \leq 10^{12}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H

Output

Find the minimum number of attacks Caracal needs to make before winning.

Sample Input 1

2

Sample Output 1

3

When Caracal attacks the initial monster, it disappears, and two monsters appear, each with the health of 1.

Then, Caracal can attack each of these new monsters once and win with a total of three attacks.

Sample Input 2

4

Sample Output 2

7

Sample Input 3

1000000000000

Sample Output 3

1099511627775


(defun main (h)
  (let* ((level (floor (log h 2))))
    (loop for i from 0 to level
          sum (expt 2 i))))

(main (read))


(defun simulate (x)
  (if (= x 1)
      1
      (+ 1 (* 2 (simulate (floor x 2))))))

(let ((h (read)))
  (format t "~a~%" (simulate h)))


#-swank
(unless (member :child-sbcl *features*)
  (quit
	:unix-status
	(process-exit-code
	  (run-program *runtime-pathname*
				   `("--control-stack-size" "128MB"
					 "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
					 "--eval" "(push :child-sbcl *features*)"
					 "--script" ,(namestring *load-pathname*))
				   :output t :error t :input t))))

(defmacro while (test &body body)
  `(do ()
	 ((not ,test))
	 ,@body))

(let* ((n (read))
	   (d (* 2 (read)))
	   (a (read))
	   (damage-sum 0)
	   (ans 0)
	   (monster (sort (loop repeat n collect (cons (read) (read)))
					  (lambda (a b) (< (car a) (car b)))))
	   (rp monster))
  (mapc (lambda (target)
		  (while (and rp (<= (caar rp) (+ (car target) d)))
				 (incf (cdar rp) damage-sum)
				 (setf rp (cdr rp)))
		  (when (> (- (cdr target) damage-sum) 0)
			(let ((attack-time (ceiling (- (cdr target) damage-sum) a)))
			  (incf ans attack-time)
			  (incf damage-sum (* a attack-time)))))
		monster)
  (princ ans))

Score : 600 points

Problem Statement

Silver Fox is fighting with N monsters.

The monsters are standing in a row, and we can assume them to be standing on a number line. The i-th monster, standing at the coordinate X_i, has the health of H_i.

Silver Fox can use bombs to attack the monsters.
Using a bomb at the coordinate x decreases the healths of all monsters between the coordinates x-D and x+D (inclusive) by A.
There is no way other than bombs to decrease the monster's health.

Silver Fox wins when all the monsters' healths become 0 or below.

Find the minimum number of bombs needed to win.

Constraints

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

0 \leq D \leq 10^9

1 \leq A \leq 10^9

0 \leq X_i \leq 10^9

1 \leq H_i \leq 10^9

X_i are distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N D A
X_1 H_1
:
X_N H_N

Output

Print the minimum number of bombs needed to win.

Sample Input 1

3 3 2
1 2
5 4
9 2

Sample Output 1

2

First, let us use a bomb at the coordinate 4 to decrease the first and second monsters' health by 2.

Then, use a bomb at the coordinate 6 to decrease the second and third monsters' health by 2.

Now, all the monsters' healths are 0.
We cannot make all the monsters' health drop to 0 or below with just one bomb.

Sample Input 2

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

Sample Output 2

5

We should use five bombs at the coordinate 5.

Sample Input 3

3 0 1
300000000 1000000000
100000000 1000000000
200000000 1000000000

Sample Output 3

3000000000

Watch out for overflow.


(let* ((a (read))
       (b (read))
       (x (make-string b :initial-element (code-char (+ #x30 a))))
       (y (make-string a :initial-element (code-char (+ #x30 b)))))
  (format t "~A~%" (if (< a b) x y)))

Score : 200 points

Problem Statement

Given are 1-digit positive integers a and b. Consider these two strings: the concatenation of b copies of the digit a, and the concatenation of a copies of the digit b. Which of these is lexicographically smaller?

Constraints

1 \leq a \leq 9

1 \leq b \leq 9

a and b are integers.

Input

Input is given from Standard Input in the following format:

a b

Output

Print the lexicographically smaller of the two strings. (If the two strings are equal, print one of them.)

Sample Input 1

4 3

Sample Output 1

3333

We have two strings 444 and 3333. Between them, 3333 is the lexicographically smaller.

Sample Input 2

7 7

Sample Output 2

7777777


#-swank
(unless (member :child-sbcl *features*)
  (quit
	:unix-status
	(process-exit-code
	  (run-program *runtime-pathname*
				   `("--control-stack-size" "128MB"
					 "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
					 "--eval" "(push :child-sbcl *features*)"
					 "--script" ,(namestring *load-pathname*))
				   :output t :error t :input t))))

(let ((a (read)) (b (read)))
  (if (< a b)
	(loop repeat b do (princ a))
	(loop repeat a do (princ b))))


(let ((a (read))
      (b (read)))
     (loop repeat a
           do (format t "~A" b)))


(defun low-elements (n p)
  (let ((ans 0)
        (min n)
        (buff))
    (dotimes (i n)
      (setf buff (pop p))
      (when (<= buff  min)
        (setf min buff)
        (incf ans)))
    ans))

(defun create-data ()
  (let ((n (read))
        (p))
    (dotimes (i n)
      (push (read) p))
    (values n (reverse p))))

(multiple-value-bind (n p) (create-data)
  (format t "~D~%" (low-elements n p)))

Score : 300 points

Problem Statement

Given is a permutation P_1, \ldots, P_N of 1, \ldots, N.
Find the number of integers i (1 \leq i \leq N) that satisfy the following condition:

For any integer j (1 \leq j \leq i), P_i \leq P_j.

Constraints

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

P_1, \ldots, P_N is a permutation of 1, \ldots, N.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 ... P_N

Output

Print the number of integers i that satisfy the condition.

Sample Input 1

5
4 2 5 1 3

Sample Output 1

3

i=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j holds for j = 1.

Similarly, i=5 does not satisfy the condition, either. Thus, there are three integers that satisfy the condition.

Sample Input 2

4
4 3 2 1

Sample Output 2

4

All integers i (1 \leq i \leq N) satisfy the condition.

Sample Input 3

6
1 2 3 4 5 6

Sample Output 3

1

Only i=1 satisfies the condition.

Sample Input 4

8
5 7 4 2 6 8 1 3

Sample Output 4

4

Sample Input 5

1
1

Sample Output 5

1


(let* ((n (read))
       (m (loop :repeat n :collect (read))))
  (princ (loop :for k :from 0 :upto (1- n) :count (= (elt m k) (apply #'min (cons (elt m k) (subseq m 0 k)))))))


#-swank
(unless (member :child-sbcl *features*)
  (quit
	:unix-status
	(process-exit-code
	  (run-program *runtime-pathname*
				   `("--control-stack-size" "128MB"
					 "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
					 "--eval" "(push :child-sbcl *features*)"
					 "--script" ,(namestring *load-pathname*))
				   :output t :error t :input t))))

(let* ((n (read))
	  (line (loop repeat n collect (read)))
	  (ans 0))
  (reduce (lambda (mins x)
			(if (< mins x)
			  mins
			  (progn
				(incf ans)
				x)))
			line
			:initial-value (expt 10 10))
  (princ ans))


;; -*- 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))
         (table (make-array '(10 10)
                            :element-type 'uint31
                            :initial-element 0)))
    (loop for x from 1 to n
          for first = (mod x 10)
          do (unless (zerop first)
               (let ((last x))
                 (loop (let ((tmp (floor last 10)))
                         (when (zerop tmp)
                           (return))
                         (setq last tmp)))
                 (incf (aref table first last)))))
    #>table
    (let ((res 0))
      (loop for i from 1 to 9
            do (loop for j from 1 to 9
                     do (incf res (* (aref table i j)
                                     (aref table j i)))))
      (println res))))

#-swank (main)

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

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

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    ;; (run-program "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 "25
"
    "17
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "1
"
    "1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "100
"
    "108
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2020
"
    "40812
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "200000
"
    "400000008
")))

Score : 400 points

Problem Statement

Given is a positive integer N.

Find the number of pairs (A, B) of positive integers not greater than N that satisfy the following condition:

When A and B are written in base ten without leading zeros, the last digit of A is equal to the first digit of B, and the first digit of A is equal to the last digit of B.

Constraints

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

25

Sample Output 1

17

The following 17 pairs satisfy the condition: (1,1), (1,11), (2,2), (2,22), (3,3), (4,4), (5,5), (6,6), (7,7), (8,8), (9,9), (11,1), (11,11), (12,21), (21,12), (22,2), and (22,22).

Sample Input 2

1

Sample Output 2

1

Sample Input 3

100

Sample Output 3

108

Sample Input 4

2020

Sample Output 4

40812

Sample Input 5

200000

Sample Output 5

400000008


;; -*- 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
;;;
;;; Binomial coefficient with mod
;;; build: O(n)
;;; query: O(1)
;;;

;; TODO: non-global handling

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

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

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

(initialize-binom)

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

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

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

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

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

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

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

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

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

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

(declaim (ftype (function * (values simple-bit-vector &optional)) make-prime-table))
(defun make-prime-table (sup)
  "Returns a simple-bit-vector of length SUP, whose (0-based) i-th bit is 1 if i
is prime and 0 otherwise.

Example: (make-prime-table 10) => #*0011010100"
  (declare (optimize (speed 3) (safety 0)))
  (check-type sup (integer 2 (#.array-total-size-limit)))
  (let ((table (make-array sup :element-type 'bit :initial-element 0))
        (sup/64 (ceiling sup 64)))
    ;; special treatment for p = 2
    (dotimes (i sup/64)
      (setf (sb-kernel:%vector-raw-bits table i) #xAAAAAAAAAAAAAAAA))
    (setf (sbit table 1) 0
          (sbit table 2) 1)
    ;; p >= 3
    (loop for p from 3 to (+ 1 (isqrt (- sup 1))) by 2
          when (= 1 (sbit table p))
          do (loop for composite from (* p p) below sup by p
                   do (setf (sbit table composite) 0)))
    table))

;; FIXME: Currently the element type of the resultant vector is (UNSIGNED-BYTE 62).
(declaim (ftype (function * (values (simple-array (integer 0 #.most-positive-fixnum) (*))
                                    simple-bit-vector
                                    &optional))
                make-prime-sequence))
(defun make-prime-sequence (sup)
  "Returns the ascending sequence of primes smaller than SUP."
  (declare (optimize (speed 3) (safety 0)))
  (check-type sup (integer 2 (#.array-total-size-limit)))
  (let ((table (make-prime-table sup)))
    (let* ((length (count 1 table))
           (result (make-array length :element-type '(integer 0 #.most-positive-fixnum)))
           (index 0))
      (declare ((integer 0 #.most-positive-fixnum) length))
      (loop for x below sup
            when (= 1 (sbit table x))
            do (setf (aref result index) x)
               (incf index))
      (values result table))))

(defstruct (prime-data (:constructor %make-prime-data (seq table)))
  (seq nil :type (simple-array (integer 0 #.most-positive-fixnum) (*)))
  (table nil :type simple-bit-vector))

(defun make-prime-data (sup)
  (multiple-value-call #'%make-prime-data (make-prime-sequence sup)))

(declaim (inline factorize)
         (ftype (function * (values list &optional)) factorize))
(defun factorize (x prime-data)
  "Returns the associative list of prime factors of X, which is composed
of (<prime> . <exponent>). E.g. (factorize 100 <prime-table>) => '((2 . 2) (5
. 5)).

- Any numbers beyond the range of PRIME-DATA are regarded as prime.
- The returned list is in descending order w.r.t. prime factors."
  (declare (integer x))
  (setq x (abs x))
  (when (<= x 1)
    (return-from factorize nil))
  (let ((prime-seq (prime-data-seq prime-data))
        result)
    (loop for prime of-type unsigned-byte across prime-seq
          do (when (= x 1)
               (return-from factorize result))
             (loop for exponent of-type (integer 0 #.most-positive-fixnum) from 0
                   do (multiple-value-bind (quot rem) (floor x prime)
                        (if (zerop rem)
                            (setf x quot)
                            (progn
                              (when (> exponent 0)
                                (push (cons prime exponent) result))
                              (loop-finish))))))
    (if (= x 1)
        result
        (cons (cons x 1) result))))

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(define-mod-operations +mod+)
(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (pdata (make-prime-data 10000))
         (as (make-array n :element-type 'uint31))
         (lcm-table (make-hash-table :size 1000 :test #'eq)))
    (dotimes (i n)
      (setf (aref as i) (read-fixnum))
      (dolist (node (factorize (aref as i) pdata))
        (let ((prime (car node))
              (exp (cdr node)))
          (declare (uint31 prime exp))
          (if (gethash prime lcm-table)
              (maxf (the uint31 (gethash prime lcm-table)) exp)
              (setf (gethash prime lcm-table) exp)))))
    (let ((lcm 1))
      (declare (uint31 lcm))
      (maphash (lambda (prime exp)
                 (declare (uint31 prime exp))
                 (dotimes (_ exp)
                   (mulfmod lcm prime)))
               lcm-table)
      (let ((res 0))
        (declare (uint62 res))
        (loop for a across as
              do (incf res (mod* lcm (aref *inv* a))))
        (println (mod res +mod+))))))

#-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 "3
2 3 4
"
    "13
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "5
12 12 12 12 12
"
    "5
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
1000000 999999 999998
"
    "996989508
")))

Score : 500 points

Problem Statement

Given are N positive integers A_1,...,A_N.

Consider positive integers B_1, ..., B_N that satisfy the following condition.

Condition: For any i, j such that 1 \leq i < j \leq N, A_i B_i = A_j B_j holds.

Find the minimum possible value of B_1 + ... + B_N for such B_1,...,B_N.

Since the answer can be enormous, print the sum modulo (10^9 +7).

Constraints

1 \leq N \leq 10^4

1 \leq A_i \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N

Output

Print the minimum possible value of B_1 + ... + B_N for B_1,...,B_N that satisfy the condition, modulo (10^9 +7).

Sample Input 1

3
2 3 4

Sample Output 1

13

Let B_1=6, B_2=4, and B_3=3, and the condition will be satisfied.

Sample Input 2

5
12 12 12 12 12

Sample Output 2

5

We can let all B_i be 1.

Sample Input 3

3
1000000 999999 999998

Sample Output 3

996989508

Print the sum modulo (10^9+7).


(defparameter N (read))
(defparameter lst
  (loop repeat N do (read)))
(defparameter const (+ 7 (expt 10 9)))

(defun calc (lst)
  (let ((l (apply #'lcm lst)))
       (mod (apply #'+
                   (mapcar #'(lambda (x) (mod (/ l x) const))
                           lst))
            const)))

(format t "~A" (calc lst))


;; -*- 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
;;;
;;; Memoization macro
;;;

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

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

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

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

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

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

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

(defmacro 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 get-path (graph u v)
  (labels ((dfs (path)
             (when (= v (car path))
               (return-from get-path (reverse path)))
             (let ((parent (or (second path) -1)))
               (dolist (child (aref graph (car path)))
                 (unless (= child parent)
                   (dfs (cons child path)))))))
    (dfs (list u))))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (graph (make-array n :element-type 'list :initial-element nil))
         (edge-table (make-array (list n n) :element-type 'uint8)))
    (dotimes (i (- n 1))
      (let ((a (- (read) 1))
            (b (- (read) 1)))
        #>graph
        (push a (aref graph b))
        (push b (aref graph a))
        (setf (aref edge-table a b) i
              (aref edge-table b a) i)))
    #>graph
    (let* ((m (read))
           ;; 辺eを塗ると満たせる制約の集合
           (constraints (make-array (- n 1) :element-type 'uint31 :initial-element 0)))
      (dotimes (constr-index m)
        (let* ((u (- (read) 1))
               (v (- (read) 1))
               (path (get-path graph u v)))
          (assert (>= (length path) 2))
          (loop for (a b) on path
                until (null b)
                do (let ((edge-index (aref edge-table a b)))
                     (setf (ldb (byte 1 constr-index)
                                (aref constraints edge-index))
                           1)))))
      #>constraints
      (with-cache (:array (#.(ash 1 20) 50) :element-type 'fixnum :initial-element -1)
        ;; edge0, ..., x-1まで見て制約の集合Sを満たしている
        (labels ((dp (s x)
                   (if (zerop x)
                       (if (zerop s) 1 0)
                       ;; x-1を塗ると満たせる制約の集合
                       (let* ((constr (aref constraints (- x 1)))
                              ;; その反転
                              (inv (logxor #xffffffff constr)))
                         (+ (dp s (- x 1)) ;; 塗らない場合
                            (dp (logand s inv) (- x 1)))))))
          (println (dp (- (ash 1 m) 1) (- n 1))))))))

#-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 "3
1 2
2 3
1
1 3
"
    "3
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
1 2
1
1 2
"
    "1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "5
1 2
3 2
3 4
5 3
3
1 3
2 4
2 5
"
    "9
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "8
1 2
2 3
4 3
2 5
6 3
6 7
8 6
5
2 7
3 5
1 6
2 8
7 8
"
    "62
")))

Score : 600 points

Problem Statement

We have a tree with N vertices numbered 1 to N.
The i-th edge in this tree connects Vertex a_i and Vertex b_i.

Consider painting each of these edges white or black. There are 2^{N-1} such ways to paint the edges. Among them, how many satisfy all of the following M restrictions?

The i-th (1 \leq i \leq M) restriction is represented by two integers u_i and v_i, which mean that the path connecting Vertex u_i and Vertex v_i must contain at least one edge painted black.

Constraints

2 \leq N \leq 50

1 \leq a_i,b_i \leq N

The graph given in input is a tree.

1 \leq M \leq \min(20,\frac{N(N-1)}{2})

1 \leq u_i < v_i \leq N

If i \not= j, either u_i \not=u_j or v_i\not=v_j

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}
M
u_1 v_1
:
u_M v_M

Output

Print the number of ways to paint the edges that satisfy all of the M conditions.

Sample Input 1

3
1 2
2 3
1
1 3

Sample Output 1

3

The tree in this input is shown below:

All of the M restrictions will be satisfied if Edge 1 and 2 are respectively painted (white, black), (black, white), or (black, black), so the answer is 3.

Sample Input 2

2
1 2
1
1 2

Sample Output 2

1

The tree in this input is shown below:

All of the M restrictions will be satisfied only if Edge 1 is painted black, so the answer is 1.

Sample Input 3

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

Sample Output 3

9

The tree in this input is shown below:

Sample Input 4

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

Sample Output 4

62

The tree in this input is shown below:


(defparameter H (parse-integer (read-line)))
(defparameter W (parse-integer (read-line)))
(defparameter N (parse-integer (read-line)))

(format t "~A" (ceiling (/ N (max H W))))

Score : 100 points

Problem Statement

We have a grid with H rows and W columns, where all the squares are initially white.

You will perform some number of painting operations on the grid.
In one operation, you can do one of the following two actions:

Choose one row, then paint all the squares in that row black.

Choose one column, then paint all the squares in that column black.

At least how many operations do you need in order to have N or more black squares in the grid?
It is guaranteed that, under the conditions in Constraints, having N or more black squares is always possible by performing some number of operations.

Constraints

1 \leq H \leq 100

1 \leq W \leq 100

1 \leq N \leq H \times W

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H
W
N

Output

Print the minimum number of operations needed.

Sample Input 1

3
7
10

Sample Output 1

2

You can have 14 black squares in the grid by performing the "row" operation twice, on different rows.

Sample Input 2

14
12
112

Sample Output 2

8

Sample Input 3

2
100
200

Sample Output 3

2


#-swank
(unless (member :child-sbcl *features*)
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "128MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))

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

(defun convert (x r)
  (list (- x r) (+ x r)))

(defun check (r1 r2)
  (<= (apply #'+ r1) (apply #'- r2)))

(defun remove-lst (x lst)
  (remove-if #'(lambda (a) (equal a x))
             lst))

(defun confirm (lst)
  (loop for i from 1 below (1- N)
        do ()))

(defparameter N (parse-integer (read-line)))
(defparameter robots
  (sort (loop for i from 0 below N
              collect (apply #'convert
                             (mapcar #'parse-integer
                                     (split " " (read-line)))))
        #'< :key #'car))

(defun hoge (lst)
  (loop with count = N
        for i from 1 below N
        do (if (< (cadr (nth (1- i) lst))
                  (car (nth i lst)))
               (progn (decf count)
                      (incf i)))
        finally (return count)))

(format t "~A" (hoge robots))

Score : 200 points

Problem Statement

In a factory, there are N robots placed on a number line.
Robot i is placed at coordinate X_i and can extend its arms of length L_i in both directions, positive and negative.

We want to remove zero or more robots so that the movable ranges of arms of no two remaining robots intersect.
Here, for each i (1 \leq i \leq N), the movable range of arms of Robot i is the part of the number line between the coordinates X_i - L_i and X_i + L_i, excluding the endpoints.

Find the maximum number of robots that we can keep.

Constraints

1 \leq N \leq 100,000

0 \leq X_i \leq 10^9 (1 \leq i \leq N)

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

If i \neq j, X_i \neq X_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 L_1
X_2 L_2
\vdots
X_N L_N

Output

Print the maximum number of robots that we can keep.

Sample Input 1

4
2 4
4 3
9 3
100 5

Sample Output 1

3

By removing Robot 2, we can keep the other three robots.

Sample Input 2

2
8 20
1 10

Sample Output 2

1

Sample Input 3

5
10 1
2 1
4 1
6 1
8 1

Sample Output 3

5