(in-package :cl-user)
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx opt
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

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

(defconstant +mod+ 1000000007)

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

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

;; BEGIN_INSERTED_CONTENTS
(defpackage :cp/read-fixnum
  (:use :cl)
  (:export #:read-fixnum))
(in-package :cp/read-fixnum)

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

(defpackage :cp/modify-macro
  (:use :cl)
  (:export #:minf #:maxf #:mulf #:divf #:iorf #:xorf #:andf))
(in-package :cp/modify-macro)

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

;; BEGIN_USE_PACKAGE
(eval-when (:compile-toplevel :load-toplevel :execute)
  (use-package :cp/modify-macro :cl-user))
(eval-when (:compile-toplevel :load-toplevel :execute)
  (use-package :cp/read-fixnum :cl-user))
(in-package :cl-user)

;;;
;;; Body
;;;

(defun main ()
  (declare #.cl-user::opt)
  (let* ((r (read))
         (c (read))
         (k (read))
         (plan (make-array '(3001 3001) :element-type 'uint31 :initial-element 0))
         (dp0 (make-array 3001 :element-type 'uint62 :initial-element 0))
         (dp1 (make-array 3001 :element-type 'uint62 :initial-element 0))
         (dp2 (make-array 3001 :element-type 'uint62 :initial-element 0))
         (dp3 (make-array 3001 :element-type 'uint62 :initial-element 0)))
    (declare (uint31 r c k))
    (dotimes (i k)
      (let ((r (read-fixnum))
            (c (read-fixnum))
            (v (read-fixnum)))
        (setf (aref plan r c) v)))
    (loop for i from 1 to r
          do (loop for j from 1 to c
                   for v = (aref plan i j)
                   do (let ((value 0))
                        (declare (uint62 value))
                        (maxf value (aref dp3 j))
                        (maxf value (aref dp0 (- j 1)))
                        (setf (aref dp0 j) value))
                      (let ((value 0))
                        (declare (uint62 value))
                        (maxf value (aref dp0 j))
                        (maxf value (+ v (aref dp3 j)))
                        (maxf value (+ v (aref dp0 (- j 1))))
                        (maxf value (aref dp1 (- j 1)))
                        (setf (aref dp1 j) value))
                      (let ((value 0))
                        (declare (uint62 value))
                        (maxf value (aref dp1 j))
                        (maxf value (+ v (aref dp1 (- j 1))))
                        (maxf value (aref dp2 (- j 1)))
                        (setf (aref dp2 j) value))
                      (let ((value 0))
                        (declare (uint62 value))
                        (maxf value (aref dp2 j))
                        (maxf value (+ v (aref dp2 (- j 1))))
                        (maxf value (aref dp3 (- j 1)))
                        (setf (aref dp3 j) value))))
    (println (aref dp3 c))))

#-swank (main)

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (equal "8
"
          (run "2 2 3
1 1 3
2 1 4
1 2 5
" nil)))
  (it.bese.fiveam:is
   (equal "29
"
          (run "2 5 5
1 1 3
2 4 20
1 2 1
1 3 4
1 4 2
" nil)))
  (it.bese.fiveam:is
   (equal "142
"
          (run "4 5 10
2 5 12
1 5 12
2 3 15
1 2 20
1 1 28
2 4 26
3 2 27
4 5 21
3 5 10
1 3 10
" nil))))


;小数の形の文字列を入力すると
;分数にして返す関数
(defun dec2frac (str)
  (loop for x across str
        with den = 0 and num = 0 and bool = nil

        if #1=(digit-char-p x)
        do (setf num (+ (* 10 num) #1#))

        if bool do (incf den)
        else do (setf bool (eq x #\.))

        finally
        (setf den (expt 10 den))
        (return (/ num den))))

(defun solve (l)
  (loop for l2 on l
        for x in l
        sum (loop for y in (cdr l2)
                  count (integerp (* x y)))))

(princ (solve (loop repeat (read)
                    collect (dec2frac (read-line)))))

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

Score : 300 points

Problem Statement

You are given N real values A_1, A_2, \ldots, A_N.
Compute the number of pairs of indices (i, j)
such that i < j and the product A_i \cdot A_j is integer.

Constraints

2 \leq N \leq 200\,000

0 < A_i < 10^4

A_i is given with at most 9 digits after the decimal.

Input

Input is given from Standard Input in the following format.

N
A_1
A_2
\vdots
A_N

Output

Print the number of pairs with integer product A_i \cdot A_j (and i < j).

Sample Input 1

5
7.5
2.4
17.000000001
17
16.000000000

Sample Output 1

3

There are 3 pairs with integer product:

7.5 \cdot 2.4 = 18

7.5 \cdot 16 = 120

17 \cdot 16 = 272

Sample Input 2

11
0.9
1
1
1.25
2.30000
5
70
0.000000001
9999.999999999
0.999999999
1.000000001

Sample Output 2

8

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.


Score : 100 points

Problem Statement

You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above.

The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner?

Constraints

-40 \leq X \leq 40

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print Yes if you will turn on the air conditioner; print No otherwise.

Sample Input 1

25

Sample Output 1

No

Sample Input 2

30

Sample Output 2

Yes


(defun main ()
  (let* ((n (read))
	 (d (read))
	 (x (make-array (list n 2)))
	 (ans 0))
    (dotimes (i n)
      (setf (aref x i 0) (read))
      (setf (aref x i 1) (read)))
    (loop for i from 0 below n
       if (>= d (sqrt (+ (expt (aref x i 0) 2) (expt (aref x i 1) 2))))
	 do (incf ans))
    (format t "~a~%" ans)))
(main)

Score : 200 points

Problem Statement

We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i).

Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there?

We remind you that the distance between the origin and the point (p, q) can be represented as \sqrt{p^2+q^2}.

Constraints

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

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

|X_i|,|Y_i| \leq 2\times 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N D
X_1 Y_1
\vdots
X_N Y_N

Output

Print an integer representing the number of points such that the distance from the origin is at most D.

Sample Input 1

4 5
0 5
-2 4
3 4
4 -4

Sample Output 1

3

The distance between the origin and each of the given points is as follows:

\sqrt{0^2+5^2}=5

\sqrt{(-2)^2+4^2}=4.472\ldots

\sqrt{3^2+4^2}=5

\sqrt{4^2+(-4)^2}=5.656\ldots

Thus, we have three points such that the distance from the origin is at most 5.

Sample Input 2

12 3
1 1
1 1
1 1
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Sample Output 2

7

Multiple points may exist at the same coordinates.

Sample Input 3

20 100000
14309 -32939
-56855 100340
151364 25430
103789 -113141
147404 -136977
-37006 -30929
188810 -49557
13419 70401
-88280 165170
-196399 137941
-176527 -61904
46659 115261
-153551 114185
98784 -6820
94111 -86268
-30401 61477
-55056 7872
5901 -163796
138819 -185986
-69848 -96669

Sample Output 3

6


(let ((n (read))
    (kyorid (read))
    (ans 0))

    (loop for i below n do
        (let ((x (read))
            (y (read)))
            (if (>= kyorid (sqrt (+ (* x x) (* y y))))
            (incf ans))
        )
    )
    (princ ans)
)


(let* ((n (read))
       (c (coerce (loop repeat n collect (read-char)) 'vector))
       (l 0)
       (r (1- (length c)))
       (count 0))
  (loop do (loop until (eql (aref c l) #\W)
                 while (< l r)
                 do (incf l))
        do (loop until (eql (aref c r) #\R)
                 while (< l r)
                 do (decf r))
        while (< l r)
        do (setf (aref c l) #\R
                 (aref c r) #\W
                 count (1+ count)
                 l (1+ l)
                 r (1- r)))
  (format t "~A~%" count))

Score : 400 points

Problem Statement

An altar enshrines N stones arranged in a row from left to right. The color of the i-th stone from the left (1 \leq i \leq N) is given to you as a character c_i; R stands for red and W stands for white.

You can do the following two kinds of operations any number of times in any order:

Choose two stones (not necessarily adjacent) and swap them.

Choose one stone and change its color (from red to white and vice versa).

According to a fortune-teller, a white stone placed to the immediate left of a red stone will bring a disaster. At least how many operations are needed to reach a situation without such a white stone?

Constraints

2 \leq N \leq 200000

c_i is R or W.

Input

Input is given from Standard Input in the following format:

N
c_{1}c_{2}...c_{N}

Output

Print an integer representing the minimum number of operations needed.

Sample Input 1

4
WWRR

Sample Output 1

2

For example, the two operations below will achieve the objective.

Swap the 1-st and 3-rd stones from the left, resulting in RWWR.

Change the color of the 4-th stone from the left, resulting in RWWW.

Sample Input 2

2
RR

Sample Output 2

0

It can be the case that no operation is needed.

Sample Input 3

8
WRWWRWRR

Sample Output 3

3


#|
------------------------------------
|               Utils               |
------------------------------------
|#

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

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

(defconstant +mod+ 1000000007)

(defmacro define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~a" b)) () '(signed-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~a" b)) () '(unsigned-byte ,b))) bits)))

(define-int-types 2 4 8 16 32 64)

(declaim (inline println))
(defun println (obj &optional (stream *standard-output*))
  (let ((*read-default-float-format* 'double-float))
    (prog1
        (write obj :stream stream)
      (fresh-line stream))))

(defmacro safe-sort (list test &key (key #'identity))
  `(progn
    (declaim (inline sort sb-impl::stable-sort-list))
    (sort (copy-seq ,list) ,test :key ,key)))

(defmacro read-numbers-to-list (size)
  `(loop repeat ,size collect (read)))

(defmacro read-numbers-to-array (size)
  (let ((i (gensym))
        (arr (gensym)))
    `(let ((,arr (make-array ,size
                             :element-type 'fixnum)))
       (declare ((array fixnum 1) ,arr))
       (loop for ,i of-type fixnum below ,size do
            (setf (aref ,arr ,i) (read))
          finally
            (return ,arr)))))

(defmacro read-characters-to-board (row-size column-size)
  (let ((board (gensym))
        (r (gensym))
        (c (gensym))
        (tmp (gensym)))
    `(let ((,board (make-array '(,row-size ,column-size) :element-type 'character :adjustable nil)))
       (dotimes (,r ,row-size ,board)
         (let ((,tmp (read-line)))
           (dotimes (,c ,column-size)
             (setf (aref ,board ,r ,c) (char ,tmp ,c))))))))

(defmethod princ-for-each-line ((sequence list))
  (format t "~{~a~&~}" sequence))

(defmethod princ-for-each-line ((sequence vector))
  (loop for i below (length sequence) do
       (princ (aref sequence i))
       (fresh-line)))

(declaim (inline unwrap))
(defun unwrap (list)
  (the string
       (format nil "~{~a~^ ~}" list)))

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

(defmacro maxf (place cand)
  `(setf ,place (max ,place ,cand)))

(defmacro minf (place cand)
  `(setf ,place (min ,place ,cand)))

(defmacro alambda (parms &body body)
  `(labels ((self ,parms ,@body))
     #'self))

(defun iota (count &optional (start 0) (step 1))
  (loop for i from 0 below count collect (+ start (* i step))))

#|
------------------------------------
|               Body               |
------------------------------------
|#

(defun solve (k xs)
  (labels ((calc-proc (len x)
             (max (1- (ceiling len x))
                  0))
           (judge (x)
             (<= (reduce #'+
                         (mapcar (lambda (s)
                                   (calc-proc s x))
                                 xs))
                 k)))
    (loop
       with ok = (expt 10 9)
       with ng = 0
       until (<= (abs (- ok ng)) 1)
       do
         (let ((mid (floor (+ ok ng) 2)))
           (if (judge mid)
               (setq ok mid)
               (setq ng mid)))
       finally
         (return ok))))

(defun main ()
  (declare #.OPT)
  (let ((n (read))
        (k (read)))
    (let ((xs (read-numbers-to-list n)))
      (princ (solve k xs))
      (fresh-line))))

#-swank (main)

Score : 500 points

Problem Statement

We have N logs of lengths A_1,A_2,\cdots A_N.

We can cut these logs at most K times in total. When a log of length L is cut at a point whose distance from an end of the log is t (0<t<L), it becomes two logs of lengths t and L-t.

Find the shortest possible length of the longest log after at most K cuts, and print it after rounding up to an integer.

Constraints

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

0 \leq K \leq 10^9

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_N

Output

Print an integer representing the answer.

Sample Input 1

2 3
7 9

Sample Output 1

4

First, we will cut the log of length 7 at a point whose distance from an end of the log is 3.5, resulting in two logs of length 3.5 each.

Next, we will cut the log of length 9 at a point whose distance from an end of the log is 3, resulting in two logs of length 3 and 6.

Lastly, we will cut the log of length 6 at a point whose distance from an end of the log is 3.3, resulting in two logs of length 3.3 and 2.7.

In this case, the longest length of a log will be 3.5, which is the shortest possible result. After rounding up to an integer, the output should be 4.

Sample Input 2

3 0
3 4 5

Sample Output 2

5

Sample Input 3

10 10
158260522 877914575 602436426 24979445 861648772 623690081 433933447 476190629 262703497 211047202

Sample Output 3

292638192


(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx opt
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

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

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

(in-package :cl-user)

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun calc (as max)
  (declare ((simple-array uint31 (*)) as)
           (uint31 max))
  (loop for a across as
        sum (- (ceiling a max) 1)))

(defun main ()
  (let* ((n (read))
         (k (read))
         (as (make-array n :element-type 'uint31 :initial-element 0)))
    (dotimes (i n)
      (setf (aref as i) (read-fixnum)))
    (sb-int:named-let bisect ((ng 0) (ok (reduce #'max as)))
      (if (<= (- ok ng) 1)
          (println ok)
          (let ((mid (floor (+ ng ok) 2)))
            (if (<= (calc as mid) k)
                (bisect ng mid)
                (bisect mid ok)))))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2 3
7 9
"
    "4
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3 0
3 4 5
"
    "5
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "10 10
158260522 877914575 602436426 24979445 861648772 623690081 433933447 476190629 262703497 211047202
"
    "292638192
")))


(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx opt
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

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

;; BEGIN_INSERTED_CONTENTS
;;;
;;; Persistent segment tree
;;;

;; TODO:
;; - abstraction
;; - test
;; - linear-time initialization
;; - avoid sb-int:power-of-two-ceiling
;; - out-of-bound error

(defparameter *store* (make-array 110000000 :element-type t))
(declaim ((simple-array t (*)) *store*)
         (always-bound *store*))
(defparameter *end* 0)
(declaim ((mod #.array-total-size-limit) *end*)
         (always-bound *end*))

(declaim (inline node-value))
(defun node-value (node)
  (the fixnum (aref *store* node)))
(declaim (inline (setf node-value)))
(defun (setf node-value) (new-value node)
  (declare (fixnum new-value))
  (setf (aref *store* node) new-value))
(declaim (inline node-left))
(defun node-left (node)
  (declare ((mod #.array-total-size-limit) node))
  (aref *store* (+ node 1)))
(declaim (inline (setf node-left)))
(defun (setf node-left) (new-value node)
  (setf (aref *store* (+ node 1)) new-value))
(declaim (inline node-right))
(defun node-right (node)
  (declare ((mod #.array-total-size-limit) node))
  (aref *store* (+ node 2)))
(declaim (inline (setf node-right)))
(defun (setf node-right) (new-value node)
  (setf (aref *store* (+ node 2)) new-value))

(declaim (inline make-node))
(defun make-node (&optional (value 0))
  (let ((end *end*))
    (when (= end (length *store*))
      (setq *store* (adjust-array *store* (* 2 end))))
    (setf (aref *store* end) value
          (aref *store* (+ end 1)) -1
          (aref *store* (+ end 2)) -1)
    (incf *end* 3)
    end))

(declaim (inline copy-node))
(defun copy-node (node)
  (let ((end *end*))
    (when (= end (length *store*))
      (setq *store* (adjust-array *store* (* 2 end))))
    (setf (aref *store* end) (aref *store* node)
          (aref *store* (+ end 1)) (aref *store* (+ node 1))
          (aref *store* (+ end 2)) (aref *store* (+ node 2)))
    (incf *end* 3)
    end))

(defstruct (psegtree (:constructor %make-psegtree)
                     (:conc-name %psegtree-))
  (length 0 :type (mod #.array-total-size-limit))
  (root 0 :type (mod #.array-total-size-limit)))

(defun make-psegtree (length)
  "Note that the actual length becomes a power of two."
  (declare ((integer 0 #.most-positive-fixnum) length))
  (let ((n (ash 1 (integer-length (- length 1))))) ; power of two ceiling
    (labels ((recur (i)
               (declare ((integer 0 #.most-positive-fixnum) i))
               (when (<= i n)
                 (let ((node (make-node)))
                   (setf (node-left node) (recur (ash i 1))
                         (node-right node) (recur (ash i 1)))
                   node))))
      (%make-psegtree :length length :root (recur 1)))))

(defun psegtree-query (psegtree left right)
  "Queries the sum of the interval [LEFT, RIGHT)."
  (declare #.opt
           ((integer 0 #.most-positive-fixnum) left right))
  (labels ((recur (root l r)
             (declare ((integer 0 #.most-positive-fixnum) l r)
                      (values fixnum &optional))
             (cond ((or (<= right l) (<= r left))
                    0)
                   ((and (<= left l) (<= r right))
                    (node-value root))
                   (t
                    (+ (recur (node-left root) l (ash (+ l r) -1))
                       (recur (node-right root) (ash (+ l r) -1) r))))))
    (recur (%psegtree-root psegtree)
           0
           (sb-int:power-of-two-ceiling (%psegtree-length psegtree)))))

(defun psegtree-inc (psegtree index delta)
  "Returns a new psegtree updated by PSEGTREE[INDEX] += DELTA. This function is
non-destructive."
  (declare #.opt
           ((integer 0 #.most-positive-fixnum) index)
           (fixnum delta))
  (labels ((recur (root l r)
             (declare ((integer 0 #.most-positive-fixnum) l r))
             (cond ((or (<= (+ index 1) l) (<= r index)))
                   ((and (<= index l) (<= r (+ index 1)))
                    (incf (node-value root) delta))
                   (t
                    (let ((new-lnode (copy-node (node-left root)))
                          (new-rnode (copy-node (node-right root))))
                      (setf (node-left root) new-lnode
                            (node-right root) new-rnode)
                      (recur new-lnode l (ash (+ l r) -1))
                      (recur new-rnode (ash (+ l r) -1) r)
                      (setf (node-value root)
                            (+ (node-value (node-left root))
                               (node-value (node-right root)))))))))
    (let ((new-psegtree (copy-psegtree psegtree))
          (new-root (copy-node (%psegtree-root psegtree))))
      (recur new-root 0 (sb-int:power-of-two-ceiling (%psegtree-length psegtree)))
      (setf (%psegtree-root new-psegtree) new-root)
      new-psegtree)))

(defmethod print-object ((object psegtree) stream)
  (print-unreadable-object (object stream :type t)
    (let ((init t)
          (length (%psegtree-length object)))
      (labels ((recur (node index)
                 (if (node-left node)
                     (progn
                       (recur (node-left node) (ash index 1))
                       (recur (node-right node) (+ (ash index 1) 1)))
                     (when (< index length)
                       (if init
                           (setq init nil)
                           (write-char #\  stream))
                       (write (node-value node) :stream stream)))))
        (recur (%psegtree-root object) 0)))))

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

(in-package :cl-user)

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defconstant +nan+ #x7fffffff)

(defun main ()
  (declare #.opt)
  (let* ((n (read))
         (q (read))
         (cs (make-array n :element-type 'uint31 :initial-element 0))
         (ls (make-array q :element-type 'uint31 :initial-element 0))
         (rs (make-array q :element-type 'uint31 :initial-element 0))
         (appeared (make-array (+ n 1) :element-type 'uint31 :initial-element +nan+))
         (psegtrees (make-array (+ n 1) :element-type t)))
    (dotimes (i n)
      (setf (aref cs i) (read-fixnum)))
    (dotimes (i q)
      (setf (aref ls i) (- (read-fixnum) 1)
            (aref rs i) (read-fixnum)))
    (setf (aref psegtrees 0) (make-psegtree n))
    (dotimes (i n)
      (let ((c (aref cs i)))
        (setf (aref psegtrees (+ i 1))
              (psegtree-inc (aref psegtrees i) i 1))
        (unless (= +nan+ (aref appeared c))
          (setf (aref psegtrees (+ i 1))
                (psegtree-inc (aref psegtrees (+ i 1)) (aref appeared c) -1)))
        (setf (aref appeared c) i)))
    (write-string
     (with-output-to-string (*standard-output* nil :element-type 'base-char)
       (loop for l across ls
             for r across rs
             for psegtree = (aref psegtrees r)
             do (println (psegtree-query psegtree l r)))))))

;; #+linux
;; (eval-when (:compile-toplevel :load-toplevel :execute)
;;   (require :sb-sprof))
;; #+linux
;; (sb-sprof:start-profiling)

#-swank (main)

;; #+linux
;; (progn
;;   (sb-sprof:stop-profiling)
;;   (sb-sprof:report))

#-swank (main)

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

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

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

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

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

#+swank
(defun gen-dat ()
  (uiop:with-output-file (out *dat-pathname* :if-exists :supersede)
    (let ((n 500000)
          (q 500000))
      (format out "~D ~D~%" n q)
      (dotimes (_ n)
        (println (+ 1 (random 500000)) out))
      (dotimes (_ q)
        (let ((l (+ 1 (random 500000)))
              (r (+ 1 (random 500000))))
          (when (> l r)
            (rotatef l r))
          (format out "~D ~D~%" l r))))))

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

Score : 600 points

Problem Statement

We have N colored balls arranged in a row from left to right; the color of the i-th ball from the left is c_i.

You are given Q queries. The i-th query is as follows: how many different colors do the l_i-th through r_i-th balls from the left have?

Constraints

1\leq N,Q \leq 5 \times 10^5

1\leq c_i \leq N

1\leq l_i \leq r_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
c_1 c_2 \cdots c_N
l_1 r_1
l_2 r_2
:
l_Q r_Q

Output

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

Sample Input 1

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

Sample Output 1

2
3
1

The 1-st, 2-nd, and 3-rd balls from the left have the colors 1, 2, and 1 - two different colors.

The 2-st, 3-rd, and 4-th balls from the left have the colors 2, 1, and 3 - three different colors.

The 3-rd ball from the left has the color 1 - just one color.

Sample Input 2

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

Sample Output 2

1
2
2
1
2
2
6
3
3
3


(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx opt
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

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

;; BEGIN_INSERTED_CONTENTS
;;;
;;; 1-dimensional binary indexed tree on arbitrary commutative monoid
;;;

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

Defines no structure; BIT is just a vector. This macro defines the three
functions: <NAME>-UPDATE!, point-update function, <NAME>-FOLD, query function for
prefix sum, and COERCE-TO-<NAME>!, constructor. If ORDER is specified, this
macro in addition defines <NAME>-BISECT-LEFT and <NAME>-BISECT-RIGHT, the
bisection functions for prefix sums. (Note that these functions work only when
the sequence of prefix sums (VECTOR[0], VECTOR[0]+VECTOR[1], ...) is monotone.)

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

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

       (declaim (inline ,fname-coerce))
       (defun ,fname-coerce (vector)
         "Destructively constructs BIT from VECTOR. (You doesn't need to call
this constructor if what you need is a `zero-filled' BIT, because a vector
filled with the identity element is a valid BIT as it is.)"
         (loop with len = (length vector)
               for i below len
               for dest-i = (logior i (+ i 1))
               when (< dest-i len)
               do (setf (aref vector dest-i)
                        (funcall ,operator (aref vector dest-i) (aref vector i)))
               finally (return vector)))

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

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

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

(in-package :cl-user)

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defconstant +nan+ #x7fffffff)
(defun main ()
  (declare #.opt
           (inline sort))
  (let* ((n (read))
         (q (read))
         (cs (make-array n :element-type 'uint31 :initial-element 0))
         (ls (make-array q :element-type 'uint31 :initial-element 0))
         (rs (make-array q :element-type 'uint31 :initial-element 0))
         (ords (make-array q :element-type 'uint31 :initial-element 0)))
    (dotimes (i n)
      (setf (aref cs i) (read-fixnum)))
    (dotimes (i q)
      (setf (aref ords i) i))
    (dotimes (i q)
      (setf (aref ls i) (- (read-fixnum) 1)
            (aref rs i) (read-fixnum)))
    (setq ords (sort ords #'< :key (lambda (i) (aref rs i))))
    (let ((appeared (make-array (+ n 1) :element-type 'uint31 :initial-element +nan+))
          (bitree (make-array n :element-type 'uint31 :initial-element 0))
          (res (make-array q :element-type 'uint31 :initial-element 0))
          (pos 0))
      (loop for i across ords
            for l = (aref ls i)
            for r = (aref rs i)
            do (loop while (< pos r)
                     for c = (aref cs pos)
                     do (bitree-update! bitree pos 1)
                        (unless (= +nan+ (aref appeared c))
                          (bitree-update! bitree (aref appeared c) -1))
                        (setf (aref appeared c) pos)
                        (incf pos))
               (setf (aref res i)
                     (- (bitree-fold bitree r)
                        (bitree-fold bitree l))))
      (write-string
       (with-output-to-string (*standard-output* nil :element-type 'base-char)
         (map () #'println res))))))

#-swank (main)

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

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

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

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

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

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

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

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

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


(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx opt
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

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

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

;;;
;;; Persistent segment tree
;;;

;; TODO:
;; - abstraction
;; - test
;; - linear-time initialization
;; - avoid sb-int:power-of-two-ceiling
;; - out-of-bound error

(declaim (inline make-node))
(defstruct (node (:constructor make-node (&optional (value 0))))
  (value 0 :type fixnum)
  (left nil :type (or null node))
  (right nil :type (or null node)))

(defstruct (psegtree (:constructor %make-psegtree)
                     (:conc-name %psegtree-))
  (length 0 :type (integer 0 #.most-positive-fixnum))
  (root nil :type node))

(defun make-psegtree (length)
  "Note that the actual length becomes a power of two."
  (declare ((integer 0 #.most-positive-fixnum) length))
  (let ((n (ash 1 (integer-length (- length 1))))) ; power of two ceiling
    (labels ((recur (i)
               (declare ((integer 0 #.most-positive-fixnum) i))
               (when (<= i n)
                 (let ((node (make-node)))
                   (setf (node-left node) (recur (ash i 1))
                         (node-right node) (recur (ash i 1)))
                   node))))
      (%make-psegtree :length length :root (recur 1)))))

(defun psegtree-query (psegtree left right)
  "Queries the sum of the interval [LEFT, RIGHT)."
  (declare ((integer 0 #.most-positive-fixnum) left right))
  (labels ((recur (root l r)
             (declare ((integer 0 #.most-positive-fixnum) l r)
                      (values fixnum &optional))
             (cond ((or (<= right l) (<= r left))
                    0)
                   ((and (<= left l) (<= r right))
                    (node-value root))
                   (t
                    (+ (recur (node-left root) l (ash (+ l r) -1))
                       (recur (node-right root) (ash (+ l r) -1) r))))))
    (recur (%psegtree-root psegtree)
           0
           (sb-int:power-of-two-ceiling (%psegtree-length psegtree)))))

(defun psegtree-update (psegtree index delta)
  "Returns a new psegtree updated by PSEGTREE[INDEX] += DELTA. This function is
non-destructive."
  (declare ((integer 0 #.most-positive-fixnum) index)
           (fixnum delta))
  (labels ((recur (root l r)
             (declare ((integer 0 #.most-positive-fixnum) l r))
             (cond ((or (<= (+ index 1) l) (<= r index)))
                   ((and (<= index l) (<= r (+ index 1)))
                    (incf (node-value root) delta))
                   (t
                    (let ((new-lnode (copy-node (node-left root)))
                          (new-rnode (copy-node (node-right root))))
                      (setf (node-left root) new-lnode
                            (node-right root) new-rnode)
                      (recur new-lnode l (ash (+ l r) -1))
                      (recur new-rnode (ash (+ l r) -1) r)
                      (setf (node-value root)
                            (+ (node-value (node-left root))
                               (node-value (node-right root)))))))))
    (let ((new-psegtree (copy-psegtree psegtree))
          (new-root (copy-node (%psegtree-root psegtree))))
      (recur new-root 0 (sb-int:power-of-two-ceiling (%psegtree-length psegtree)))
      (setf (%psegtree-root new-psegtree) new-root)
      new-psegtree)))

(defmethod print-object ((object psegtree) stream)
  (print-unreadable-object (object stream :type t)
    (let ((init t)
          (length (%psegtree-length object)))
      (labels ((recur (node index)
                 (if (node-left node)
                     (progn
                       (recur (node-left node) (ash index 1))
                       (recur (node-right node) (+ (ash index 1) 1)))
                     (when (< index length)
                       (if init
                           (setq init nil)
                           (write-char #\  stream))
                       (write (node-value node) :stream stream)))))
        (recur (%psegtree-root object) 0)))))

(in-package :cl-user)

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun solve (n q as ls rs)
  (declare (uint31 n q)
           ((simple-array uint31 (*)) as ls rs))
  (let ((prevs (make-array n :element-type 'int32 :initial-element 0))
        (table (make-array n :element-type 'int32 :initial-element -1)))
    (dotimes (i n)
      (let ((a (aref as i)))
        (setf (aref prevs i) (aref table a)
              (aref table a) i)))
    #>prevs
    (let ((psegtrees (make-array (+ n 1) :element-type t)))
      (setf (aref psegtrees 0) (make-psegtree n))
      (dotimes (i n)
        (let ((prev (aref prevs i)))
          (setf (aref psegtrees (+ i 1))
                (psegtree-update (aref psegtrees i) (+ prev 1) 1))))
      #>psegtrees
      (let ((res (make-array q :element-type 'uint31 :initial-element 0)))
        (dotimes (i q)
          (let* ((r (aref rs i))
                 (l (aref ls i))
                 (psegtree-r (aref psegtrees r))
                 (psegtree-l (aref psegtrees l))
                 (r-value (psegtree-query psegtree-r 0 (max 1 (+ l 1))))
                 (l-value (psegtree-query psegtree-l 0 (max 1 (+ l 1)))))
            (dbg psegtree-r psegtree-l r-value l-value)
            (setf (aref res i) (- r-value l-value))))
        res))))

(defun main ()
  (let* ((n (read))
         (q (read))
         (cs (make-array n :element-type 'uint31 :initial-element 0))
         (ls (make-array q :element-type 'uint31 :initial-element 0))
         (rs (make-array q :element-type 'uint31 :initial-element 0)))
    (dotimes (i n)
      (setf (aref cs i) (read-fixnum)))
    (dotimes (i q)
      (setf (aref ls i) (- (read-fixnum) 1)
            (aref rs i) (read-fixnum)))
    (let ((res (solve n q cs ls rs)))
      (write-string
       (with-output-to-string (*standard-output* nil :element-type 'base-char)
         (map () #'println res))))))

#-swank (main)

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

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

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

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

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

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

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

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

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


Score: 100 points

Problem Statement

M-kun is a competitor in AtCoder, whose highest rating is X.

In this site, a competitor is given a kyu (class) according to his/her highest rating. For ratings from 400 through 1999, the following kyus are given:

From 400 through 599: 8-kyu

From 600 through 799: 7-kyu

From 800 through 999: 6-kyu

From 1000 through 1199: 5-kyu

From 1200 through 1399: 4-kyu

From 1400 through 1599: 3-kyu

From 1600 through 1799: 2-kyu

From 1800 through 1999: 1-kyu

What kyu does M-kun have?

Constraints

400 \leq X \leq 1999

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the kyu M-kun has, as an integer.
For example, if he has 8-kyu, print 8.

Sample Input 1

725

Sample Output 1

7

M-kun's highest rating is 725, which corresponds to 7-kyu.

Thus, 7 is the correct output.

Sample Input 2

1600

Sample Output 2

2

M-kun's highest rating is 1600, which corresponds to 2-kyu.

Thus, 2 is the correct output.


(defun f (a ll)
  (if (= a 0)
      (if (and (< (first ll) (second ll))
               (< (second ll) (third ll)))
          ll nil)
      (or (f (1- a) `(,(* 2 (first ll)) ,(second ll) ,(third ll)))
          (f (1- a) `(,(first ll) ,(* 2 (second ll)) ,(third ll)))
          (f (1- a) `(,(first ll) ,(second ll) ,(* 2 (third ll)))))))

(let* ((n (list (read) (read) (read)))
       (m (read)))
  (if (f m　n)
      (princ "Yes")
      (princ "No")))

Score: 200 points

Problem Statement

M-kun has the following three cards:

A red card with the integer A.

A green card with the integer B.

A blue card with the integer C.

He is a genius magician who can do the following operation at most K times:

Choose one of the three cards and multiply the written integer by 2.

His magic is successful if both of the following conditions are satisfied after the operations:

The integer on the green card is strictly greater than the integer on the red card.

The integer on the blue card is strictly greater than the integer on the green card.

Determine whether the magic can be successful.

Constraints

1 \leq A, B, C \leq 7

1 \leq K \leq 7

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C
K

Output

If the magic can be successful, print Yes; otherwise, print No.

Sample Input 1

7 2 5
3

Sample Output 1

Yes

The magic will be successful if, for example, he does the following operations:

First, choose the blue card. The integers on the red, green, and blue cards are now 7, 2, and 10, respectively.

Second, choose the green card. The integers on the red, green, and blue cards are now 7, 4, and 10, respectively.

Third, choose the green card. The integers on the red, green, and blue cards are now 7, 8, and 10, respectively.

Sample Input 2

7 4 2
3

Sample Output 2

No

He has no way to succeed in the magic with at most three operations.


(defun main ()
  (let ((a (read))
	(b (read))
	(c (read))
	(k (read))
	(ans "No"))
    (dotimes (i k)
      (cond ((< a b c) (setf c (* c 2)))
	    ((>= a c) (setf c (* c 2)))
	    ((>= a b) (setf b (* b 2)))
	    ((>= b c) (setf c (* c 2)))))
    (if (< a b c )
	(setf ans "Yes"))
    (format t "~a~%" ans)))
(main)


(let ((a (read))
      (b (read))
      (c (read))
      (k (read)))
  (loop until (> b a)
        while (> k 0)
        do (setf k (1- k)
                 b (* b 2)))
  (loop until (> c b)
        while (> k 0)
        do (setf k (1- k)
                 c (* c 2)))
  (format t "~A~%"
          (if (< a b c)
              "Yes"
              "No")))


(let* ((n (read))
    (k (read))
    (a (make-array n :initial-element 0))
    (hyoten (make-array k :initial-element 1)))

    (dotimes (i n)
        (setf (aref a i) (read))
    )

    (loop for i below (- n k) do
            (if (< (aref a i) (aref a (+ i k)))
                (format t "Yes~%")
                (format t "No~%")
            )
    )
)

Score: 300 points

Problem Statement

M-kun is a student in Aoki High School, where a year is divided into N terms.

There is an exam at the end of each term. According to the scores in those exams, a student is given a grade for each term, as follows:

For the first through (K-1)-th terms: not given.

For each of the K-th through N-th terms: the multiplication of the scores in the last K exams, including the exam in the graded term.

M-kun scored A_i in the exam at the end of the i-th term.

For each i such that K+1 \leq i \leq N, determine whether his grade for the i-th term is strictly greater than the grade for the (i-1)-th term.

Constraints

2 \leq N \leq 200000

1 \leq K \leq N-1

1 \leq A_i \leq 10^{9}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 A_3 \ldots A_N

Output

Print the answer in N-K lines.

The i-th line should contain Yes if the grade for the (K+i)-th term is greater than the grade for the (K+i-1)-th term, and No otherwise.

Sample Input 1

5 3
96 98 95 100 20

Sample Output 1

Yes
No

His grade for each term is computed as follows:

3-rd term: (96 \times 98 \times 95) = 893760

4-th term: (98 \times 95 \times 100) = 931000

5-th term: (95 \times 100 \times 20) = 190000

Sample Input 2

3 2
1001 869120 1001

Sample Output 2

No

Note that the output should be No if the grade for the 3-rd term is equal to the grade for the 2-nd term.

Sample Input 3

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

Sample Output 3

Yes
Yes
No
Yes
Yes
No
Yes
Yes


(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx opt
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

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

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

(in-package :cl-user)

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (let* ((n (read))
         (as (make-array (+ n 1) :element-type 'uint31 :initial-element 0))
         (dp (make-array (+ n 1) :element-type 'uint62 :initial-element 0)))
    (dotimes (i n)
      (setf (aref as (+ i 1)) (read)))
    (setf (aref dp 0) 1000)
    (dotimes (x n)
      (unless (zerop (aref dp x))
        ;; dest(-1)日に株をすべて売却するとする
        (loop for dest from (+ x 2) to n
              for mid = (+ x 1) ; この日にできるだけ株を買う
              do (loop for i from mid below dest
                       when (< (aref as i) (aref as mid))
                       do (setq mid i))
                 (multiple-value-bind (stock-delta rem) (floor (aref dp x) (aref as mid))
                   (maxf (aref dp dest)
                         (+ rem (* stock-delta (aref as dest))))))))
    (println (reduce #'max dp))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "7
100 130 130 130 115 115 150
"
    "1685
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "6
200 180 160 140 120 100
"
    "1000
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
157 193
"
    "1216
")))

Score: 400 points

Problem Statement

To become a millionaire, M-kun has decided to make money by trading in the next N days. Currently, he has 1000 yen and no stocks - only one kind of stock is issued in the country where he lives.

He is famous across the country for his ability to foresee the future. He already knows that the price of one stock in the next N days will be as follows:

A_1 yen on the 1-st day, A_2 yen on the 2-nd day, ..., A_N yen on the N-th day.

In the i-th day, M-kun can make the following trade any number of times (possibly zero), within the amount of money and stocks that he has at the time.

Buy stock: Pay A_i yen and receive one stock.

Sell stock: Sell one stock for A_i yen.

What is the maximum possible amount of money that M-kun can have in the end by trading optimally?

Constraints

2 \leq N \leq 80

100 \leq A_i \leq 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N

Output

Print the maximum possible amount of money that M-kun can have in the end, as an integer.

Sample Input 1

7
100 130 130 130 115 115 150

Sample Output 1

1685

In this sample input, M-kun has seven days of trading. One way to have 1685 yen in the end is as follows:

Initially, he has 1000 yen and no stocks.

Day 1: Buy 10 stocks for 1000 yen. Now he has 0 yen.

Day 2: Sell 7 stocks for 910 yen. Now he has 910 yen.

Day 3: Sell 3 stocks for 390 yen. Now he has 1300 yen.

Day 4: Do nothing.

Day 5: Buy 1 stock for 115 yen. Now he has 1185 yen.

Day 6: Buy 10 stocks for 1150 yen. Now he has 35 yen.

Day 7: Sell 11 stocks for 1650 yen. Now he has 1685 yen.

There is no way to have 1686 yen or more in the end, so the answer is 1685.

Sample Input 2

6
200 180 160 140 120 100

Sample Output 2

1000

In this sample input, it is optimal to do nothing throughout the six days, after which we will have 1000 yen.

Sample Input 3

2
157 193

Sample Output 3

1216

In this sample input, it is optimal to buy 6 stocks in Day 1 and sell them in Day 2, after which we will have 1216 yen.


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

(defmacro dphash (name args &body expr)
  `(let ((table (make-hash-table :test #'equal)))
     (defun  ,name ,args
       (or (gethash (list ,@args) table)
           (setf (gethash (list ,@args) table)
                 (progn
                   ,@expr))))))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(defun main (n xp yp ps)
  (let ((res (make-array (list (1+ n)) :initial-element (expt 10 10))))
    (labels ((f (cost xs ys &optional (used 0))
               (if xs
                   (min (f cost (cdr xs) (cdr ys) used)
                        (f (mapcar #'min cost
                                   (mapcar (lambda (x) (abs (- x (car xs))))
                                           xp))
                           (cdr xs)
                           (cdr ys)
                           (1+ used))
                        (f (mapcar #'min cost
                                   (mapcar (lambda (y) (abs (- y (car ys))))
                                           yp))
                           (cdr xs)
                           (cdr ys)
                           (1+ used)))
                   (setf (aref res used)
                         (min (aref res used)
                              (reduce #'+
                                      (mapcar #'* cost ps)))))))
      (f (mapcar #'min
                 (mapcar #'abs xp)
                 (mapcar #'abs yp))
         xp
         yp)
      (coerce res 'list))))

#-swank
(let* ((n (read))
       (lists (collect-times n (read-times 3))))
  (format t "~{~a~%~}"
          (apply #'main
                 (cons n
                       (map-0-n (lambda (p) (mapcar (lambda (list) (nth p list))
                                                    lists))
                                3)))))

Score: 500 points

Problem Statement

New AtCoder City has an infinite grid of streets, as follows:

At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.

A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.

A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.

There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.

The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.

M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.

Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.

M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.

For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?

Constraints

1 \leq N \leq 15

-10 \ 000 \leq X_i \leq 10 \ 000

-10 \ 000 \leq Y_i \leq 10 \ 000

1 \leq P_i \leq 1 \ 000 \ 000

The locations of the N residential areas, (X_i, Y_i), are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N

Output

Print the answer in N+1 lines.

The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.

Sample Input 1

3
1 2 300
3 3 600
1 4 800

Sample Output 1

2900
900
0
0

When K = 0, the residents of Area 1, 2, and 3 have to walk the distances of 1, 3, and 1, respectively, to reach a railroad.

Thus, the sum of the walking distances of all citizens, S, is 1 \times 300 + 3 \times 600 + 1 \times 800 = 2900.

When K = 1, if we build a railroad along the street corresponding to the line y = 4 in the coordinate plane, the walking distances of the citizens of Area 1, 2, and 3 become 1, 1, and 0, respectively.

Then, S = 1 \times 300 + 1 \times 600 + 0 \times 800 = 900.

We have many other options for where we build the railroad, but none of them makes S less than 900.

When K = 2, if we build a railroad along the street corresponding to the lines x = 1 and x = 3 in the coordinate plane, all citizens can reach a railroad with the walking distance of 0, so S = 0. We can also have S = 0 when K = 3.

The figure below shows the optimal way to build railroads for the cases K = 0, 1, 2.

The street painted blue represents the roads along which we build railroads.

Sample Input 2

5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400

Sample Output 2

13800
1600
0
0
0
0

The figure below shows the optimal way to build railroads for the cases K = 1, 2.

Sample Input 3

6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200

Sample Output 3

26700
13900
3200
1200
0
0
0

The figure below shows the optimal way to build railroads for the case K = 3.

Sample Input 4

8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903

Sample Output 4

2576709
1569381
868031
605676
366338
141903
0
0
0

The figure below shows the optimal way to build railroads for the case K = 4.


(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx opt
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

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

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

;;;
;;; Sort multiple vectors
;;;

;; TODO: throw an error if there are two ore more identical vectors in the given
;; vectors

(declaim (inline %median3))
(defun %median3 (x y z order)
  (if (funcall order x y)
      (if (funcall order y z)
          y
          (if (funcall order z x)
              x
              z))
      (if (funcall order z y)
          y
          (if (funcall order x z)
              x
              z))))

(defun parallel-sort! (vector order &rest vectors)
  "Destructively sorts VECTOR w.r.t. ORDER and applies the same permutation to
all the vectors in VECTORS.

Note: not randomized; shuffle the inputs if necessary"
  (declare (vector vector))
  (labels
      ((recur (left right)
         (when (< left right)
           (let* ((l left)
                  (r right)
                  (pivot (%median3 (aref vector l)
                                   (aref vector (ash (+ l r) -1))
                                   (aref vector r)
                                   order)))
             (declare ((integer 0 #.most-positive-fixnum) l r))
             (loop (loop while (funcall order (aref vector l) pivot)
                         do (incf l 1))
                   (loop while (funcall order pivot (aref vector r))
                         do (decf r 1))
                   (when (>= l r)
                     (return))
                   (rotatef (aref vector l) (aref vector r))
                   (dolist (v vectors)
                     (rotatef (aref v l) (aref v r)))
                   (incf l 1)
                   (decf r 1))
             (recur left (- l 1))
             (recur (+ r 1) right)))))
    (recur 0 (- (length vector) 1))
    vector))

#+sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-c:define-source-transform parallel-sort! (vector order &rest vectors)
    (let ((vec (gensym))
          (vecs (loop for _ in vectors collect (gensym))))
      `(let ((,vec ,vector)
             ,@(loop for v in vectors
                     for sym in vecs
                     collect `(,sym ,v)))
         (labels
             ((recur (left right)
                (when (< left right)
                  (let* ((l left)
                         (r right)
                         (pivot (%median3 (aref ,vec l)
                                          (aref ,vec (ash (+ l r) -1))
                                          (aref ,vec r)
                                          ,order)))
                    (declare ((integer 0 #.most-positive-fixnum) l r))
                    (loop (loop while (funcall ,order (aref ,vec l) pivot)
                                do (incf l 1))
                          (loop while (funcall ,order pivot (aref ,vec r))
                                do (decf r 1))
                          (when (>= l r)
                            (return))
                          (rotatef (aref ,vec l) (aref ,vec r))
                          ,@(loop for sym in vecs
                                  collect `(rotatef (aref ,sym l) (aref ,sym r)))
                          (incf l 1)
                          (decf r 1))
                    (recur left (- l 1))
                    (recur (+ r 1) right)))))
           (recur 0 (- (length ,vec) 1))
           ,vec)))))

(defun parallel-shuffle! (vector &rest vectors)
   "Destructively shuffles VECTOR and applies the same permutation to all the
vectors in VECTORS."
  (loop for i from (- (length vector) 1) above 0
        for j = (random (+ i 1))
        do (rotatef (aref vector i) (aref vector j))
           (dolist (v vectors)
             (rotatef (aref v i) (aref v j)))
        finally (return vector)))

#+sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-c:define-source-transform parallel-shuffle! (vector &rest vectors)
    (let ((vec (gensym))
          (vecs (loop for _ in vectors collect (gensym))))
      `(let ((,vec ,vector)
             ,@(loop for v in vectors
                     for sym in vecs
                     collect `(,sym ,v)))
         (loop for i from (- (length ,vec) 1) above 0
               for j = (random (+ i 1))
               do (rotatef (aref ,vec i) (aref ,vec j))
                  ,@(loop for sym in vecs
                          collect `(rotatef (aref ,sym i) (aref ,sym j)))
               finally (return ,vec))))))

(in-package :cl-user)

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun solve (n xs ys ps k seconds)
  (declare #.OPT
           ((simple-array int32 (*)) xs ys ps)
           (uint8 n k))
  (let ((on-set (make-array k :element-type 'int32 :initial-element 0))
        (off-set (make-array n :element-type 'int32 :initial-element 0))
        ;; 0: horizontal, 1: vertical
        (dirs (make-array k :element-type 'bit :initial-element 0)))
    (parallel-shuffle! xs ys ps)
    (dotimes (i n)
      (if (< i k)
          (setf (aref on-set i) i
                (aref dirs i) (random 2))
          (setf (aref off-set (- i k)) i)))
    (labels ((calc-score ()
               (loop for x across xs
                     for y across ys
                     for p across ps
                     sum (* p (min (loop for idx across on-set
                                         for dir across dirs
                                         minimize (if (zerop dir)
                                                      (abs (- y (aref ys idx)))
                                                      (abs (- x (aref xs idx)))))
                                   (abs y)
                                   (abs x)))
                     of-type fixnum)))
      (let* ((min-score (calc-score))
             (current-score min-score)
             (count 0))
        (declare (fixnum min-score current-score))
        (sb-int:with-progressive-timeout (get-remaining-time :seconds seconds)
          (loop (minf min-score current-score)
                (when (eq 0 (get-remaining-time))
                  (return min-score))
                (let ((i (random k))
                      (j (random (- n k)))
                      (flip (random 2)))
                  (rotatef (aref on-set i) (aref off-set j))
                  (xorf (aref dirs i) flip)
                  (let ((score (calc-score)))
                    (if (<= score current-score)
                        (setq current-score score)
                        (progn
                          (rotatef (aref on-set i) (aref off-set j))
                          (xorf (aref dirs i) flip)))))))))))

(defun main ()
  (let* ((n (read))
         (xs (make-array n :element-type 'int32 :initial-element 0))
         (ys (make-array n :element-type 'int32 :initial-element 0))
         (ps (make-array n :element-type 'int32 :initial-element 0)))
    (dotimes (i n)
      (setf (aref xs i) (read)
            (aref ys i) (read)
            (aref ps i) (read)))
    (println (loop for x across xs
                   for y across ys
                   for p across ps
                   sum (* p (min (abs x) (abs y)))))
    (loop for k from 1 below n
          do (println (if (member k (list 1 2 (- n 1) (- n 2)))
                          (solve n xs ys ps k 0.02d0)
                          (solve n xs ys ps k 0.28d0))))
    (when (> n 1)
      (println 0))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
1 2 300
3 3 600
1 4 800
"
    "2900
900
0
0
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400
"
    "13800
1600
0
0
0
0
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200
"
    "26700
13900
3200
1200
0
0
0
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903
"
    "2576709
1569381
868031
605676
366338
141903
0
0
0
")))