(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)
#-swank (disable-debugger) ; for CS Academy

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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(declaim (inline bisect-right))
(defun bisect-right (target value &key (start 0) end)
  (declare (integer start)
           ((or null integer) end))
  (macrolet
      ((frob (accessor &optional declaration)
         `(labels
              ((%bisect-right (ng ok)
                 ;; TARGET[OK] > VALUE always holds (assuming
                 ;; TARGET[END] = +infinity)
                 ,@(when declaration (list declaration))
                 (if (<= (- ok ng) 1)
                     ok
                     (let ((mid (ash (+ ng ok) -1)))
                       (if (< value (the fixnum (cdr (,accessor target mid))))
                           (%bisect-right ng mid)
                           (%bisect-right mid ok))))))
            (assert (<= start end))
            (%bisect-right (- start 1) end))))
    (etypecase target
      (vector
       (let ((end (or end (length target))))
         (frob aref (declare ((integer -1 (#.array-total-size-limit)) ng ok)))))
      (function
       (assert end () "Requires END argument if TARGET is a function.")
       (frob funcall)))))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (boundary 10)
         (vs (make-array n :element-type 'uint31 :initial-element 0))
         (ws (make-array n :element-type 'uint31 :initial-element 0)))
    (declare (uint31 n boundary))
    (dotimes (i n)
      (setf (aref vs i) (read-fixnum)
            (aref ws i) (read-fixnum)))
    (let* ((q (read))
           (query-store (make-array n :element-type 'list :initial-element nil))
           (res (make-array q :element-type 'fixnum :initial-element 0)))
      (dotimes (i q)
        (let ((v (- (read-fixnum) 1))
              (l (read-fixnum)))
          (push (list v l i) (aref query-store v))))
      (labels ((%merge (half-vs half-ws v w)
                 (declare ((simple-array uint31 (*)) half-vs half-ws)
                          (uint31 v w))
                 (let* ((new-vs (make-array (* 2 (length half-vs)) :element-type 'uint31))
                        (new-ws (make-array (* 2 (length half-ws)) :element-type 'uint31))
                        (len (length half-vs))
                        (pos1 0)
                        (pos2 0)
                        (end 0)
                        (current-w -1)
                        (current-v -1))
                   (declare ((simple-array uint31 (*)) new-vs new-ws)
                            (uint31 pos1 pos2 end)
                            (int32 current-w current-v))
                   (loop (when (= pos1 len)
                           (loop for pos from pos2 below len
                                 for v2 = (aref half-vs pos)
                                 for w2 = (aref half-ws pos)
                                 when (and (> (+ v2 v) current-v)
                                           (> (+ w2 w) current-w))
                                 do (setf (aref new-vs end) (+ v2 v)
                                          (aref new-ws end) (+ w2 w)
                                          end (+ end 1)
                                          current-w (+ w2 w)
                                          current-v (+ v2 v)))
                           (return))
                         (let ((v1 (aref half-vs pos1))
                               (w1 (aref half-ws pos1))
                               (v2 (aref half-vs pos2))
                               (w2 (aref half-ws pos2)))
                           (declare (uint31 v1 v2 w1 w2))
                           (cond ((< w1 (+ w2 w))
                                  (when (and (> w1 current-w)
                                             (> v1 current-v))
                                    (setf (aref new-vs end) v1
                                          (aref new-ws end) w1
                                          end (+ end 1)
                                          current-w w1
                                          current-v v1))
                                  (incf pos1))
                                 ((> w1 (+ w2 w))
                                  (when (and (> (+ w2 w) current-w)
                                             (> (+ v2 v) current-v))
                                    (setf (aref new-vs end) (+ v2 v)
                                          (aref new-ws end) (+ w2 w)
                                          end (+ end 1)
                                          current-w (+ w2 w)
                                          current-v (+ v2 v)))
                                  (incf pos2))
                                 ((= w1 (+ w2 w))
                                  (let ((max-v (max v1 (+ v2 v))))
                                    (declare (uint31 max-v))
                                    (when (and (> w1 current-w)
                                               (> max-v current-v))
                                      (setf (aref new-vs end) max-v
                                            (aref new-ws end) w1
                                            end (+ end 1)
                                            current-w w1
                                            current-v max-v))
                                    (incf pos1)
                                    (incf pos2)))
                                 (t (error "Huh?")))))
                   (values (adjust-array new-vs end)
                           (adjust-array new-ws end)))))
        (sb-int:named-let recur ((i 0)
                                 (depth 0)
                                 (half-vs1 (make-array 1
                                                       :element-type 'uint31
                                                       :initial-element 0))
                                 (half-ws1 (make-array 1
                                                       :element-type 'uint31
                                                       :initial-element 0))
                                 (half-vs2 (make-array 1
                                                       :element-type 'uint31
                                                       :initial-element 0))
                                 (half-ws2 (make-array 1
                                                       :element-type 'uint31
                                                       :initial-element 0)))
          (declare (uint31 i depth)
                   ((simple-array uint31 (*)) half-vs1 half-ws1 half-vs2 half-ws2))
          (when (>= i n) (return-from recur))
          (let ((v (aref vs i))
                (w (aref ws i)))
            (declare (uint31 v w))
            (if (< depth boundary)
                (multiple-value-bind (half-vs1 half-ws1) (%merge half-vs1 half-ws1 v w)
                  (declare ((simple-array uint31 (*)) half-vs1 half-ws1))
                  (loop for (q-v q-l index) of-type (uint31 uint31 uint31) in (aref query-store i)
                        do (setf (aref res index)
                                 (loop for v across half-vs1
                                       for w across half-ws1
                                       while (<= w q-l)
                                       maximize v)))
                  (recur (+ (* i 2) 1) (+ depth 1) half-vs1 half-ws1 half-vs2 half-ws2)
                  (recur (+ (* i 2) 2) (+ depth 1) half-vs1 half-ws1 half-vs2 half-ws2))
                (multiple-value-bind (half-vs2 half-ws2) (%merge half-vs2 half-ws2 v w)
                  (declare ((simple-array uint31 (*)) half-vs2 half-ws2))
                  (loop
                    for (q-v q-l index) of-type (uint31 uint31 uint31) in (aref query-store i)
                    for max-value of-type uint31 = 0
                    for pos2 = (- (length half-vs2) 1)
                    do (loop for v1 across half-vs1
                             for w1 across half-ws1
                             while (<= w1 q-l)
                             do (loop for w2 = (aref half-ws2 pos2)
                                      until (<= (+ w1 w2) q-l)
                                      do (decf pos2))
                                (let ((v2 (aref half-vs2 pos2)))
                                  (declare (uint31 v2))
                                  (maxf max-value (+ v1 v2))))
                       (setf (aref res index) max-value))
                  (recur (+ (* i 2) 1) (+ depth 1)
                         half-vs1 half-ws1 half-vs2 half-ws2)
                  (recur (+ (* i 2) 2) (+ depth 1)
                         half-vs1 half-ws1 half-vs2 half-ws2))))))
      (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)
    (run-program "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)))

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

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

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

#+swank
(defun gen-dat ()
  (uiop:with-output-file (out *dat-pathname* :if-exists :supersede)
    (let ((n 262143))
      (format out "~D~%" n)
      (dotimes (_ n)
        (format out "~D ~D~%" (+ 1 (random 100000)) (+ 1 (random 100000))))
      (println 100000 out)
      (dotimes (_ 100000)
        (format out "~D ~D~%" (+ 130000 (random (- n 130000))) (+ 1 (random 100000)))))))

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
1 2
2 3
3 4
3
1 1
2 5
3 5
"
    "0
3
3
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "15
123 119
129 120
132 112
126 109
118 103
115 109
102 100
130 120
105 105
132 115
104 102
107 107
127 116
121 104
121 115
8
8 234
9 244
10 226
11 227
12 240
13 237
14 206
15 227
"
    "256
255
250
247
255
259
223
253
")))

Score : 700 points

Problem Statement

We have a rooted binary tree with N vertices, where the vertices are numbered 1 to N.
Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex \left[ \frac{i}{2} \right].

Each vertex has one item in it. The item in Vertex i has a value of V_i and a weight of W_i.
Now, process the following query Q times:

Given are a vertex v of the tree and a positive integer L.
Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L.
Find the maximum possible total value of the chosen items.

Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k (k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i.

Constraints

All values in input are integers.

1 \leq N < 2^{18}

1 \leq Q \leq 10^5

1 \leq V_i \leq 10^5

1 \leq W_i \leq 10^5

For the values v and L given in each query, 1 \leq v \leq N and 1 \leq L \leq 10^5.

Input

Let v_i and L_i be the values v and L given in the i-th query.
Then, Input is given from Standard Input in the following format:

N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q

Output

For each integer i from 1 through Q,
the i-th line should contain the response to the i-th query.

Sample Input 1

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

Sample Output 1

0
3
3

In the first query, we are given only one choice: the item with (V, W)=(1,2). Since L = 1, we cannot actually choose it, so our response should be 0.

In the second query, we are given two choices: the items with (V, W)=(1,2) and (V, W)=(2,3). Since L = 5, we can choose both of them, so our response should be 3.

Sample Input 2

15
123 119
129 120
132 112
126 109
118 103
115 109
102 100
130 120
105 105
132 115
104 102
107 107
127 116
121 104
121 115
8
8 234
9 244
10 226
11 227
12 240
13 237
14 206
15 227

Sample Output 2

256
255
250
247
255
259
223
253


(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)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
;;;
;;; Quicksort (randomized median-of-three partitioning)
;;;

;; TODO: Consider worst case of deterministic partitioning
;; Reference:
;; Hannu Erkio, The worst case permutation for median-of-three quicksort

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

(declaim (inline quicksort!))
(defun quicksort! (vector order &key (start 0) end)
  "Destructively sorts VECTOR w.r.t. ORDER."
  (declare ((simple-array list (*)) vector))
  (unless end
    (setq end (length vector)))
  (assert (<= 0 start end))
  (labels
      ((recur (left right)
         (declare (fixnum left right))
         (when (< left right)
           (let* ((l left)
                  (r right)
                  (pivot (%median3 (aref vector l)
                                   (aref vector (the fixnum (+ l (random (+ 1 (- r l))))))
                                   (aref vector r)
                                   order)))
             (declare ((integer 0 #.most-positive-fixnum) l r))
             (loop (loop while (funcall order (aref vector l) pivot)
                         do (incf l))
                   (loop while (funcall order pivot (aref vector r))
                         do (decf r))
                   (when (>= l r)
                     (return))
                   (rotatef (aref vector l) (aref vector r))
                   (incf l 1)
                   (decf r 1))
             (recur left (- l 1))
             (recur (+ r 1) right)))))
    (recur start (- end 1))
    vector))

(declaim (inline quicksort-by2!))
(defun quicksort-by2! (vector order)
  "Destructively sorts VECTOR by two elements. This function regards
each (VECTOR[i], VECTOR[i+1]) for even i as an element, and compares only the
first elements (i.e. VECTOR[i] for even i)."
  (declare (vector vector))
  (assert (evenp (length vector)))
  (labels
      ((recur (left right)
         (declare (fixnum left right))
         (when (< left right)
           (let* ((l left)
                  (r right)
                  (pivot (%median3
                          (aref vector l)
                          (aref vector (the fixnum (+ l (logandc2 (random (+ 1 (- r l))) 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 2))
                   (loop while (funcall order pivot (aref vector r))
                         do (decf r 2))
                   (when (>= l r)
                     (return))
                   (rotatef (aref vector l) (aref vector r))
                   (rotatef (aref vector (+ l 1)) (aref vector (+ r 1)))
                   (incf l 2)
                   (decf r 2))
             (recur left (- l 2))
             (recur (+ r 2) right)))))
    (recur 0 (- (length vector) 2))
    vector))

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

(declaim (inline bisect-left))
(defun bisect-left (target value &key (start 0) end (order #'<) (key #'identity))
  "TARGET := vector | function (taking an integer argument)
ORDER := strict order

Analogue of lower_bound() of C++ or bisect_left() of Python: Returns the
smallest index (or input) i that fulfills TARGET[i] >= VALUE, where '>=' is the
complement of ORDER. In other words, this function returns the leftmost index at
which VALUE can be inserted with keeping the order. Therefore, TARGET must be
monotonically non-decreasing with respect to ORDER.

- This function returns END if VALUE exceeds TARGET[END-1].
- The range [START, END) is half-open.
- END must be explicitly specified if TARGET is function.
- KEY is applied to each element of TARGET before comparison."
  (declare (function key order)
           (integer start)
           ((or null integer) end))
  (macrolet
      ((frob (accessor &optional declaration)
         `(labels
              ((%bisect-left (ng ok)
                 ;; TARGET[OK] >= VALUE always holds (assuming
                 ;; TARGET[END] = +infinity)
                 ,@(when declaration (list declaration))
                 (if (<= (- ok ng) 1)
                     ok
                     (let ((mid (ash (+ ng ok) -1)))
                       (if (funcall order (funcall key (,accessor target mid)) value)
                           (%bisect-left mid ok)
                           (%bisect-left ng mid))))))
            (assert (<= start end))
            (%bisect-left (- start 1) end))))
    (etypecase target
      (vector
       (let ((end (or end (length target))))
         (frob aref (declare ((integer -1 (#.most-positive-fixnum)) ng ok)))))
      (function
       (assert end () "Requires END argument if TARGET is a function.")
       (frob funcall)))))

(declaim (inline log2-ceil))
(defun log2-ceil (x)
  "Rounds up log2(x)."
  (let ((ceil (ceiling x)))
    (declare ((integer 0) ceil))
    (integer-length (- ceil 1))))

(declaim (inline log-ceil))
(defun log-ceil (x base)
  "Rounds up log(x)."
  (declare (real x)
           ((integer 2) base))
  (assert (>= x 0))
  (labels ((%log ()
             (nth-value 0 (ceiling (log x base)))))
    (if (integerp x)
        (let ((y x)
              (result 0))
          (loop (when (zerop y)
                  (return result))
                (multiple-value-bind (quot rem) (floor y base)
                  (unless (zerop rem)
                    (return (%log)))
                  (setq y quot)
                  (incf result))))
        (%log))))

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(declaim (inline bisect-right))
(defun bisect-right (target value &key (start 0) end)
  (declare (integer start)
           ((or null integer) end))
  (macrolet
      ((frob (accessor &optional declaration)
         `(labels
              ((%bisect-right (ng ok)
                 ;; TARGET[OK] > VALUE always holds (assuming
                 ;; TARGET[END] = +infinity)
                 ,@(when declaration (list declaration))
                 (if (<= (- ok ng) 1)
                     ok
                     (let ((mid (ash (+ ng ok) -1)))
                       (if (< value (the fixnum (cdr (,accessor target mid))))
                           (%bisect-right ng mid)
                           (%bisect-right mid ok))))))
            (assert (<= start end))
            (%bisect-right (- start 1) end))))
    (etypecase target
      (vector
       (let ((end (or end (length target))))
         (frob aref (declare ((integer -1 (#.array-total-size-limit)) ng ok)))))
      (function
       (assert end () "Requires END argument if TARGET is a function.")
       (frob funcall)))))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (boundary 9)
         (vs (make-array n :element-type 'uint31 :initial-element 0))
         (ws (make-array n :element-type 'uint31 :initial-element 0)))
    (declare (uint31 n boundary))
    (dotimes (i n)
      (setf (aref vs i) (read-fixnum)
            (aref ws i) (read-fixnum)))
    (let* ((q (read))
           (query-store (make-array n :element-type 'list :initial-element nil))
           (res (make-array q :element-type 'fixnum :initial-element 0))
           (tree (make-array (* 3 n) :element-type 'bit :initial-element 1)))
      (dotimes (i q)
        (let ((v (- (read-fixnum) 1))
              (l (read-fixnum)))
          (push (list v l i) (aref query-store v))))
      (sb-int:named-let recur ((i 0))
        (declare (uint31 i))
        (if (>= i n)
            nil
            (let ((res1 (recur (+ (* i 2) 1)))
                  (res2 (recur (+ (* i 2) 2))))
              (when (or (aref query-store i)
                        res1 res2)
                (setf (aref tree i) 1)))))
      (sb-int:named-let recur ((i 0)
                               (depth 0)
                               (half1 (list (cons 0 0)))
                               (half2 (make-array 1
                                                  :element-type 'list
                                                  :initial-element (cons 0 0))))
        (declare (uint31 i depth)
                 ((simple-array list (*)) half2))
        (when (>= i n) (return-from recur))
        (let ((v (aref vs i))
              (w (aref ws i)))
          (declare (uint31 v w))
          (if (< depth boundary)
              (let ((new-half1
                      (append (loop for (v-sum . w-sum) of-type (uint62 . uint62) in half1
                                    collect (cons (+ v-sum v) (+ w-sum w)))
                              half1)))
                (loop for (q-v q-l index) of-type (uint62 uint62 uint62) in (aref query-store i)
                      do (setf (aref res index)
                               (loop for (v1 . w1) of-type (uint62 . uint62) in new-half1
                                     when (<= w1 q-l)
                                     maximize v1)))
                (recur (+ (* i 2) 1) (+ depth 1) new-half1 half2)
                (recur (+ (* i 2) 2) (+ depth 1) new-half1 half2))
              (let ((new-half2 (make-array (length half2) :element-type 'list)))
                (dotimes (i (length half2))
                  (destructuring-bind (v-sum . w-sum) (aref half2 i)
                    (declare (uint62 v-sum w-sum))
                    (setf (aref new-half2 i)
                          (cons (+ v v-sum) (+ w w-sum)))))
                ;; #>new-half2
                (let* ((new-half2 (concatenate '(simple-array list (*))
                                               half2 new-half2)))
                  (declare ((simple-array list (*)) new-half2))
                  ;; #>new-half2
                  ;; answer query
                  ;; 各重みについて最大の価値しかいらない
                  (if (aref query-store i)
                      (progn
                        (quicksort! new-half2
                                    (lambda (node1 node2)
                                      (let ((v1 (car node1))
                                            (w1 (cdr node1))
                                            (v2 (car node2))
                                            (w2 (cdr node2)))
                                        (declare (fixnum v1 w1 v2 w2))
                                        (or (< w1 w2)
                                            (and (= w1 w2) (> v1 v2))))))
                        (let ((current-v -1)
                              (current-pos 0))
                          (dotimes (i (length new-half2))
                            (destructuring-bind (v . w) (aref new-half2 i)
                              (declare (uint62 v w))
                              (when (> v current-v)
                                (setq current-v v)
                                (setf (aref new-half2 current-pos) (aref new-half2 i))
                                (incf current-pos))))
                          (setq new-half2 (adjust-array new-half2 current-pos))
                          (loop for (q-v q-l index) of-type (uint62 uint62 uint62) in (aref query-store i)
                                for max-value of-type fixnum = 0
                                do (loop for (v1 . w1) of-type (fixnum . fixnum) in half1
                                         ;; 重さがl-w1以下のものを見つける
                                         when (<= w1 q-l)
                                         do (let ((idx (- (bisect-right new-half2
                                                                        (- q-l w1))
                                                          1)))
                                              (destructuring-bind (v2 . w2) (aref new-half2 idx)
                                                (declare (fixnum v2 w2))
                                                (maxf max-value (+ v1 v2)))))
                                   (setf (aref res index) max-value))
                          (when (= 1 (aref tree (+ (* i 2) 1)))
                            (recur (+ (* i 2) 1) (+ depth 1) half1 new-half2))
                          (when (= 1 (aref tree (+ (* i 2) 2)))
                            (recur (+ (* i 2) 2) (+ depth 1) half1 new-half2))))
                      (progn
                        (when (= 1 (aref tree (+ (* i 2) 1)))
                          (recur (+ (* i 2) 1) (+ depth 1) half1 new-half2))
                        (when (= 1 (aref tree (+ (* i 2) 2)))
                          (recur (+ (* i 2) 2) (+ depth 1) half1 new-half2)))))))))
      (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)
    (run-program "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)))

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

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

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

#+swank
(defun gen-dat ()
  (uiop:with-output-file (out *dat-pathname* :if-exists :supersede)
    (let ((n 262143))
      (format out "~D~%" n)
      (dotimes (_ n)
        (format out "~D ~D~%" (+ 1 (random 100000)) (+ 1 (random 100000))))
      (println 100000 out)
      (dotimes (_ 100000)
        (format out "~D ~D~%" (+ 1 (random n)) (+ 1 (random 100000)))))))

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
1 2
2 3
3 4
3
1 1
2 5
3 5
"
    "0
3
3
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "15
123 119
129 120
132 112
126 109
118 103
115 109
102 100
130 120
105 105
132 115
104 102
107 107
127 116
121 104
121 115
8
8 234
9 244
10 226
11 227
12 240
13 237
14 206
15 227
"
    "256
255
250
247
255
259
223
253
")))

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

Submitted source-code file size, in bytes.

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

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


(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)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
;;;
;;; Quicksort (randomized median-of-three partitioning)
;;;

;; TODO: Consider worst case of deterministic partitioning
;; Reference:
;; Hannu Erkio, The worst case permutation for median-of-three quicksort

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

(declaim (inline quicksort!))
(defun quicksort! (vector order &key (start 0) end)
  "Destructively sorts VECTOR w.r.t. ORDER."
  (declare (vector vector))
  (unless end
    (setq end (length vector)))
  (assert (<= 0 start end))
  (labels
      ((recur (left right)
         (declare (fixnum left right))
         (when (< left right)
           (let* ((l left)
                  (r right)
                  (pivot (%median3 (aref vector l)
                                   (aref vector (the fixnum (+ l (random (+ 1 (- r l))))))
                                   (aref vector r)
                                   order)))
             (declare ((integer 0 #.most-positive-fixnum) l r))
             (loop (loop while (funcall order (aref vector l) pivot)
                         do (incf l))
                   (loop while (funcall order pivot (aref vector r))
                         do (decf r))
                   (when (>= l r)
                     (return))
                   (rotatef (aref vector l) (aref vector r))
                   (incf l 1)
                   (decf r 1))
             (recur left (- l 1))
             (recur (+ r 1) right)))))
    (recur start (- end 1))
    vector))

(declaim (inline quicksort-by2!))
(defun quicksort-by2! (vector order)
  "Destructively sorts VECTOR by two elements. This function regards
each (VECTOR[i], VECTOR[i+1]) for even i as an element, and compares only the
first elements (i.e. VECTOR[i] for even i)."
  (declare (vector vector))
  (assert (evenp (length vector)))
  (labels
      ((recur (left right)
         (declare (fixnum left right))
         (when (< left right)
           (let* ((l left)
                  (r right)
                  (pivot (%median3
                          (aref vector l)
                          (aref vector (the fixnum (+ l (logandc2 (random (+ 1 (- r l))) 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 2))
                   (loop while (funcall order pivot (aref vector r))
                         do (decf r 2))
                   (when (>= l r)
                     (return))
                   (rotatef (aref vector l) (aref vector r))
                   (rotatef (aref vector (+ l 1)) (aref vector (+ r 1)))
                   (incf l 2)
                   (decf r 2))
             (recur left (- l 2))
             (recur (+ r 2) right)))))
    (recur 0 (- (length vector) 2))
    vector))

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

(declaim (inline bisect-left))
(defun bisect-left (target value &key (start 0) end (order #'<) (key #'identity))
  "TARGET := vector | function (taking an integer argument)
ORDER := strict order

Analogue of lower_bound() of C++ or bisect_left() of Python: Returns the
smallest index (or input) i that fulfills TARGET[i] >= VALUE, where '>=' is the
complement of ORDER. In other words, this function returns the leftmost index at
which VALUE can be inserted with keeping the order. Therefore, TARGET must be
monotonically non-decreasing with respect to ORDER.

- This function returns END if VALUE exceeds TARGET[END-1].
- The range [START, END) is half-open.
- END must be explicitly specified if TARGET is function.
- KEY is applied to each element of TARGET before comparison."
  (declare (function key order)
           (integer start)
           ((or null integer) end))
  (macrolet
      ((frob (accessor &optional declaration)
         `(labels
              ((%bisect-left (ng ok)
                 ;; TARGET[OK] >= VALUE always holds (assuming
                 ;; TARGET[END] = +infinity)
                 ,@(when declaration (list declaration))
                 (if (<= (- ok ng) 1)
                     ok
                     (let ((mid (ash (+ ng ok) -1)))
                       (if (funcall order (funcall key (,accessor target mid)) value)
                           (%bisect-left mid ok)
                           (%bisect-left ng mid))))))
            (assert (<= start end))
            (%bisect-left (- start 1) end))))
    (etypecase target
      (vector
       (let ((end (or end (length target))))
         (frob aref (declare ((integer -1 (#.most-positive-fixnum)) ng ok)))))
      (function
       (assert end () "Requires END argument if TARGET is a function.")
       (frob funcall)))))

(declaim (inline log2-ceil))
(defun log2-ceil (x)
  "Rounds up log2(x)."
  (let ((ceil (ceiling x)))
    (declare ((integer 0) ceil))
    (integer-length (- ceil 1))))

(declaim (inline log-ceil))
(defun log-ceil (x base)
  "Rounds up log(x)."
  (declare (real x)
           ((integer 2) base))
  (assert (>= x 0))
  (labels ((%log ()
             (nth-value 0 (ceiling (log x base)))))
    (if (integerp x)
        (let ((y x)
              (result 0))
          (loop (when (zerop y)
                  (return result))
                (multiple-value-bind (quot rem) (floor y base)
                  (unless (zerop rem)
                    (return (%log)))
                  (setq y quot)
                  (incf result))))
        (%log))))

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(declaim (inline bisect-right))
(defun bisect-right (target value &key (start 0) end (order #'<))
  (declare (function order)
           (integer start)
           ((or null integer) end))
  (macrolet
      ((frob (accessor &optional declaration)
         `(labels
              ((%bisect-right (ng ok)
                 ;; TARGET[OK] > VALUE always holds (assuming
                 ;; TARGET[END] = +infinity)
                 ,@(when declaration (list declaration))
                 (if (<= (- ok ng) 1)
                     ok
                     (let ((mid (ash (+ ng ok) -1)))
                       (if (funcall order value (the fixnum (cdr (,accessor target mid))))
                           (%bisect-right ng mid)
                           (%bisect-right mid ok))))))
            (assert (<= start end))
            (%bisect-right (- start 1) end))))
    (etypecase target
      (vector
       (let ((end (or end (length target))))
         (frob aref (declare ((integer -1 (#.array-total-size-limit)) ng ok)))))
      (function
       (assert end () "Requires END argument if TARGET is a function.")
       (frob funcall)))))

(defun main ()
  (declare #.OPT
           (inline sort))
  (let* ((n (read))
         (boundary (ash (log2-ceil n) -1))
         (vs (make-array n :element-type 'uint31 :initial-element 0))
         (ws (make-array n :element-type 'uint31 :initial-element 0)))
    (declare (uint31 n boundary))
    (dotimes (i n)
      (setf (aref vs i) (read-fixnum)
            (aref ws i) (read-fixnum)))
    (let* ((q (read))
           (query-store (make-array n :element-type 'list :initial-element nil))
           (res (make-array q :element-type 'fixnum :initial-element 0))
           (tree (make-array (* 3 n) :element-type 'bit :initial-element 1)))
      (dotimes (i q)
        (let ((v (- (read-fixnum) 1))
              (l (read-fixnum)))
          (push (list v l i) (aref query-store v))))
      (sb-int:named-let recur ((i 0))
        (if (>= i n)
            nil
            (let ((res1 (recur (+ (* i 2) 1)))
                  (res2 (recur (+ (* i 2) 2))))
              (when (or (aref query-store i)
                        res1 res2)
                (setf (aref tree i) 1)))))
      (sb-int:named-let recur ((i 0)
                               (depth 0)
                               (half1 (list (cons 0 0)))
                               (half2 (make-array 1
                                                  :element-type 'list
                                                  :initial-element (cons 0 0))))
        (declare (uint31 i depth)
                 ((simple-array list (*)) half2))
        (when (>= i n) (return-from recur))
        (let ((v (aref vs i))
              (w (aref ws i)))
          (declare (uint31 v w))
          (if (< depth boundary)
              (let ((new-half1
                      (append (loop for (v-sum . w-sum) of-type (uint62 . uint62) in half1
                                    collect (cons (+ v-sum v) (+ w-sum w)))
                              half1)))
                (loop for (q-v q-l index) of-type (uint62 uint62 uint62) in (aref query-store i)
                      do (setf (aref res index)
                               (loop for (v1 . w1) in new-half1
                                     when (<= w1 q-l)
                                     maximize v1)))
                (recur (+ (* i 2) 1) (+ depth 1) new-half1 half2)
                (recur (+ (* i 2) 2) (+ depth 1) new-half1 half2))
              (let ((new-half2 (make-array (length half2) :element-type 'list)))
                (dotimes (i (length half2))
                  (destructuring-bind (v-sum . w-sum) (aref half2 i)
                    (setf (aref new-half2 i)
                          (cons (+ v v-sum) (+ w w-sum)))))
                ;; #>new-half2
                (let* ((new-half2 (concatenate '(simple-array list (*))
                                               half2 new-half2)))
                  ;; #>new-half2
                  ;; answer query
                  ;; 各重みについて最大の価値しかいらない
                  (if (aref query-store i)
                      (progn
                        (quicksort! new-half2
                                    (lambda (node1 node2)
                                      (let ((v1 (car node1))
                                            (w1 (cdr node1))
                                            (v2 (car node2))
                                            (w2 (cdr node2)))
                                        (declare (fixnum v1 w1 v2 w2))
                                        (or (< w1 w2)
                                            (and (= w1 w2) (> v1 v2))))))
                        (let ((current-v -1)
                              (nn-half2 (make-array 0 :element-type 'list :fill-pointer 0)))
                          (dotimes (i (length new-half2))
                            (destructuring-bind (v . w) (aref new-half2 i)
                              (when (> v current-v)
                                (setq current-v v)
                                (vector-push-extend (aref new-half2 i) nn-half2))))
                          (let ((nn-half2 (coerce nn-half2 '(simple-array list (*)))))
                            (declare ((simple-array list (*)) nn-half2))
                            (loop for (q-v q-l index) of-type (uint62 uint62 uint62) in (aref query-store i)
                                  for max-value of-type fixnum = 0
                                  do (loop for (v1 . w1) of-type (fixnum . fixnum) in half1
                                           ;; 重さがl-w1以下のものを見つける
                                           when (<= w1 q-l)
                                           do (let ((idx (- (bisect-right nn-half2
                                                                          (- q-l w1))
                                                            1)))
                                                (destructuring-bind (v2 . w2) (aref nn-half2 idx)
                                                  (declare (fixnum v2 w2))
                                                  (assert (<= (+ w1 w2) q-l))
                                                  (maxf max-value (+ v1 v2)))))
                                     (setf (aref res index) max-value))
                            (when (= 1 (aref tree (+ (* i 2) 1)))
                              (recur (+ (* i 2) 1) (+ depth 1) half1 nn-half2))
                            (when (= 1 (aref tree (+ (* i 2) 2)))
                              (recur (+ (* i 2) 2) (+ depth 1) half1 nn-half2)))))
                      (progn
                        (when (= 1 (aref tree (+ (* i 2) 1)))
                          (recur (+ (* i 2) 1) (+ depth 1) half1 new-half2))
                        (when (= 1 (aref tree (+ (* i 2) 2)))
                          (recur (+ (* i 2) 2) (+ depth 1) half1 new-half2)))))))))
      (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)
    (run-program "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)))

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

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

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

#+swank
(defun gen-dat ()
  (uiop:with-output-file (out *dat-pathname* :if-exists :supersede)
    (let ((n 262144))
      (format out "~D~%" n)
      (dotimes (_ n)
        (format out "~D ~D~%" (+ 1 (random 100000)) (+ 1 (random 100000))))
      (println 100000 out)
      (dotimes (_ 100000)
        (format out "~D ~D~%" (+ 1 (random n)) (+ 1 (random 100000)))))))

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
1 2
2 3
3 4
3
1 1
2 5
3 5
"
    "0
3
3
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "15
123 119
129 120
132 112
126 109
118 103
115 109
102 100
130 120
105 105
132 115
104 102
107 107
127 116
121 104
121 115
8
8 234
9 244
10 226
11 227
12 240
13 237
14 206
15 227
"
    "256
255
250
247
255
259
223
253
")))


(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)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
;;;
;;; Quicksort (randomized median-of-three partitioning)
;;;

;; TODO: Consider worst case of deterministic partitioning
;; Reference:
;; Hannu Erkio, The worst case permutation for median-of-three quicksort

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

(declaim (inline quicksort!))
(defun quicksort! (vector order &key (start 0) end)
  "Destructively sorts VECTOR w.r.t. ORDER."
  (declare (vector vector))
  (unless end
    (setq end (length vector)))
  (assert (<= 0 start end))
  (labels
      ((recur (left right)
         (declare (fixnum left right))
         (when (< left right)
           (let* ((l left)
                  (r right)
                  (pivot (%median3 (aref vector l)
                                   (aref vector (the fixnum (+ l (random (+ 1 (- r l))))))
                                   (aref vector r)
                                   order)))
             (declare ((integer 0 #.most-positive-fixnum) l r))
             (loop (loop while (funcall order (aref vector l) pivot)
                         do (incf l))
                   (loop while (funcall order pivot (aref vector r))
                         do (decf r))
                   (when (>= l r)
                     (return))
                   (rotatef (aref vector l) (aref vector r))
                   (incf l 1)
                   (decf r 1))
             (recur left (- l 1))
             (recur (+ r 1) right)))))
    (recur start (- end 1))
    vector))

(declaim (inline quicksort-by2!))
(defun quicksort-by2! (vector order)
  "Destructively sorts VECTOR by two elements. This function regards
each (VECTOR[i], VECTOR[i+1]) for even i as an element, and compares only the
first elements (i.e. VECTOR[i] for even i)."
  (declare (vector vector))
  (assert (evenp (length vector)))
  (labels
      ((recur (left right)
         (declare (fixnum left right))
         (when (< left right)
           (let* ((l left)
                  (r right)
                  (pivot (%median3
                          (aref vector l)
                          (aref vector (the fixnum (+ l (logandc2 (random (+ 1 (- r l))) 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 2))
                   (loop while (funcall order pivot (aref vector r))
                         do (decf r 2))
                   (when (>= l r)
                     (return))
                   (rotatef (aref vector l) (aref vector r))
                   (rotatef (aref vector (+ l 1)) (aref vector (+ r 1)))
                   (incf l 2)
                   (decf r 2))
             (recur left (- l 2))
             (recur (+ r 2) right)))))
    (recur 0 (- (length vector) 2))
    vector))

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

(declaim (inline bisect-left))
(defun bisect-left (target value &key (start 0) end (order #'<) (key #'identity))
  "TARGET := vector | function (taking an integer argument)
ORDER := strict order

Analogue of lower_bound() of C++ or bisect_left() of Python: Returns the
smallest index (or input) i that fulfills TARGET[i] >= VALUE, where '>=' is the
complement of ORDER. In other words, this function returns the leftmost index at
which VALUE can be inserted with keeping the order. Therefore, TARGET must be
monotonically non-decreasing with respect to ORDER.

- This function returns END if VALUE exceeds TARGET[END-1].
- The range [START, END) is half-open.
- END must be explicitly specified if TARGET is function.
- KEY is applied to each element of TARGET before comparison."
  (declare (function key order)
           (integer start)
           ((or null integer) end))
  (macrolet
      ((frob (accessor &optional declaration)
         `(labels
              ((%bisect-left (ng ok)
                 ;; TARGET[OK] >= VALUE always holds (assuming
                 ;; TARGET[END] = +infinity)
                 ,@(when declaration (list declaration))
                 (if (<= (- ok ng) 1)
                     ok
                     (let ((mid (ash (+ ng ok) -1)))
                       (if (funcall order (funcall key (,accessor target mid)) value)
                           (%bisect-left mid ok)
                           (%bisect-left ng mid))))))
            (assert (<= start end))
            (%bisect-left (- start 1) end))))
    (etypecase target
      (vector
       (let ((end (or end (length target))))
         (frob aref (declare ((integer -1 (#.most-positive-fixnum)) ng ok)))))
      (function
       (assert end () "Requires END argument if TARGET is a function.")
       (frob funcall)))))

(declaim (inline log2-ceil))
(defun log2-ceil (x)
  "Rounds up log2(x)."
  (let ((ceil (ceiling x)))
    (declare ((integer 0) ceil))
    (integer-length (- ceil 1))))

(declaim (inline log-ceil))
(defun log-ceil (x base)
  "Rounds up log(x)."
  (declare (real x)
           ((integer 2) base))
  (assert (>= x 0))
  (labels ((%log ()
             (nth-value 0 (ceiling (log x base)))))
    (if (integerp x)
        (let ((y x)
              (result 0))
          (loop (when (zerop y)
                  (return result))
                (multiple-value-bind (quot rem) (floor y base)
                  (unless (zerop rem)
                    (return (%log)))
                  (setq y quot)
                  (incf result))))
        (%log))))

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(declaim (inline bisect-right))
(defun bisect-right (target value &key (start 0) end (order #'<))
  (declare (function order)
           (integer start)
           ((or null integer) end))
  (macrolet
      ((frob (accessor &optional declaration)
         `(labels
              ((%bisect-right (ng ok)
                 ;; TARGET[OK] > VALUE always holds (assuming
                 ;; TARGET[END] = +infinity)
                 ,@(when declaration (list declaration))
                 (if (<= (- ok ng) 1)
                     ok
                     (let ((mid (ash (+ ng ok) -1)))
                       (if (funcall order value (the fixnum (cdr (,accessor target mid))))
                           (%bisect-right ng mid)
                           (%bisect-right mid ok))))))
            (assert (<= start end))
            (%bisect-right (- start 1) end))))
    (etypecase target
      (vector
       (let ((end (or end (length target))))
         (frob aref (declare ((integer -1 (#.array-total-size-limit)) ng ok)))))
      (function
       (assert end () "Requires END argument if TARGET is a function.")
       (frob funcall)))))

(defun main ()
  (declare #.OPT
           (inline sort))
  (let* ((n (read))
         (boundary (ash (log2-ceil n) -1))
         (vs (make-array n :element-type 'uint31 :initial-element 0))
         (ws (make-array n :element-type 'uint31 :initial-element 0)))
    (declare (uint31 n boundary))
    (dotimes (i n)
      (setf (aref vs i) (read-fixnum)
            (aref ws i) (read-fixnum)))
    (let* ((q (read))
           (query-store (make-array n :element-type 'list :initial-element nil))
           (res (make-array q :element-type 'fixnum :initial-element 0)))
      (dotimes (i q)
        (let ((v (- (read-fixnum) 1))
              (l (read-fixnum)))
          (push (list v l i) (aref query-store v))))
      (sb-int:named-let recur ((i 0)
                               (depth 0)
                               (half1 (list (cons 0 0)))
                               (half2 (make-array 1
                                                  :element-type 'list
                                                  :initial-element (cons 0 0))))
        (declare (uint31 i depth)
                 ((simple-array list (*)) half2))
        (when (>= i n) (return-from recur))
        (let ((v (aref vs i))
              (w (aref ws i)))
          (declare (uint31 v w))
          (if (< depth boundary)
              (let ((new-half1
                      (append (loop for (v-sum . w-sum) of-type (uint62 . uint62) in half1
                                    collect (cons (+ v-sum v) (+ w-sum w)))
                              half1)))
                (loop for (q-v q-l index) of-type (uint62 uint62 uint62) in (aref query-store i)
                      do (setf (aref res index)
                               (loop for (v1 . w1) in new-half1
                                     when (<= w1 q-l)
                                     maximize v1)))
                (recur (+ (* i 2) 1) (+ depth 1) new-half1 half2)
                (recur (+ (* i 2) 2) (+ depth 1) new-half1 half2))
              (let ((new-half2 (make-array (length half2) :element-type 'list)))
                (dotimes (i (length half2))
                  (destructuring-bind (v-sum . w-sum) (aref half2 i)
                    (setf (aref new-half2 i)
                          (cons (+ v v-sum) (+ w w-sum)))))
                ;; #>new-half2
                (let* ((new-half2 (concatenate '(simple-array list (*))
                                               half2 new-half2)))
                  ;; #>new-half2
                  ;; answer query
                  ;; 各重みについて最大の価値しかいらない
                  (if (aref query-store i)
                      (progn
                        (quicksort! new-half2
                                    (lambda (node1 node2)
                                      (let ((v1 (car node1))
                                            (w1 (cdr node1))
                                            (v2 (car node2))
                                            (w2 (cdr node2)))
                                        (declare (fixnum v1 w1 v2 w2))
                                        (or (< w1 w2)
                                            (and (= w1 w2) (> v1 v2))))))
                        (let ((current-v -1)
                              (nn-half2 (make-array 0 :element-type 'list :fill-pointer 0)))
                          (dotimes (i (length new-half2))
                            (destructuring-bind (v . w) (aref new-half2 i)
                              (when (> v current-v)
                                (setq current-v v)
                                (vector-push-extend (aref new-half2 i) nn-half2))))
                          (let ((nn-half2 (coerce nn-half2 '(simple-array list (*)))))
                            (declare ((simple-array list (*)) nn-half2))
                            (loop for (q-v q-l index) of-type (uint62 uint62 uint62) in (aref query-store i)
                                  for max-value of-type fixnum = 0
                                  do (loop for (v1 . w1) of-type (fixnum . fixnum) in half1
                                           ;; 重さがl-w1以下のものを見つける
                                           when (<= w1 q-l)
                                           do (let ((idx (- (bisect-right nn-half2
                                                                          (- q-l w1))
                                                            1)))
                                                (destructuring-bind (v2 . w2) (aref nn-half2 idx)
                                                  (declare (fixnum v2 w2))
                                                  (assert (<= (+ w1 w2) q-l))
                                                  (maxf max-value (+ v1 v2)))))
                                     (setf (aref res index) max-value))
                            (recur (+ (* i 2) 1) (+ depth 1) half1 nn-half2)
                            (recur (+ (* i 2) 2) (+ depth 1) half1 nn-half2))))
                      (progn
                        (recur (+ (* i 2) 1) (+ depth 1) half1 new-half2)
                        (recur (+ (* i 2) 2) (+ depth 1) half1 new-half2))))))))
      (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)
    (run-program "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)))

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

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

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

#+swank
(defun gen-dat ()
  (uiop:with-output-file (out *dat-pathname* :if-exists :supersede)
    (let ((n 262144))
      (format out "~D~%" n)
      (dotimes (_ n)
        (format out "~D ~D~%" (+ 1 (random 100000)) (+ 1 (random 100000))))
      (println 100000 out)
      (dotimes (_ 100000)
        (format out "~D ~D~%" (+ 1 (random n)) (+ 1 (random 100000)))))))

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
1 2
2 3
3 4
3
1 1
2 5
3 5
"
    "0
3
3
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "15
123 119
129 120
132 112
126 109
118 103
115 109
102 100
130 120
105 105
132 115
104 102
107 107
127 116
121 104
121 115
8
8 234
9 244
10 226
11 227
12 240
13 237
14 206
15 227
"
    "256
255
250
247
255
259
223
253
")))


Score : 100 points

Problem Statement

Compute A \times B.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the value A \times B as an integer.

Sample Input 1

2 5

Sample Output 1

10

We have 2 \times 5 = 10.

Sample Input 2

100 100

Sample Output 2

10000


(defun prime-array (n) ;素数列
  (let ((arr (make-array (1+ n) :element-type 'bit :initial-element 1)))
    (setf (aref arr 0) 0)
    (setf (aref arr 1) 0)
    (loop :for q :from 1 :upto n :do(if (= 1 (aref arr q))
                                        (loop :for a :from (* 2 q) :upto n :by q :do(setf (aref arr a) 0))))
    arr))
(let* ((n (read))
       (pr (prime-array (ceiling (sqrt n))))
       (stk nil))
  (loop :for k :across pr
        :for a :from 0
        :if (and (= k 1) (= 0 (mod n a)))
          :do (push (cons a (loop :for p :from 1
                                  :if (not (= 0 (mod n (expt a p))))
                                    :return (1- p))) stk))
  (if stk
      (princ (loop :for k :in stk
                   :sum (loop :for a :from 1
                              :for b := (* 1/2 a (1+ a))
                              :if (< (cdr k) b)
                                :return (1- a))))
      (princ 1)))

Score : 400 points

Problem Statement

Given is a positive integer N. Consider repeatedly applying the operation below on N:

First, choose a positive integer z satisfying all of the conditions below:

z can be represented as z=p^e, where p is a prime number and e is a positive integer;

z divides N;

z is different from all integers chosen in previous operations.

Then, replace N with N/z.

Find the maximum number of times the operation can be applied.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum number of times the operation can be applied.

Sample Input 1

24

Sample Output 1

3

We can apply the operation three times by, for example, making the following choices:

Choose z=2 (=2^1). (Now we have N=12.)

Choose z=3 (=3^1). (Now we have N=4.)

Choose z=4 (=2^2). (Now we have N=1.)

Sample Input 2

1

Sample Output 2

0

We cannot apply the operation at all.

Sample Input 3

64

Sample Output 3

3

We can apply the operation three times by, for example, making the following choices:

Choose z=2 (=2^1). (Now we have N=32.)

Choose z=4 (=2^2). (Now we have N=8.)

Choose z=8 (=2^3). (Now we have N=1.)

Sample Input 4

1000000007

Sample Output 4

1

We can apply the operation once by, for example, making the following choice:

z=1000000007 (=1000000007^1). (Now we have N=1.)

Sample Input 5

997764507000

Sample Output 5

7


Score : 100 points

Problem Statement

In this problem, we use the 24-hour clock.

Takahashi gets up exactly at the time H_1 : M_1 and goes to bed exactly at the time H_2 : M_2. (See Sample Inputs below for clarity.)
He has decided to study for K consecutive minutes while he is up.
What is the length of the period in which he can start studying?

Constraints

0 \le H_1, H_2 \le 23

0 \le M_1, M_2 \le 59

The time H_1 : M_1 comes before the time H_2 : M_2.

K \ge 1

Takahashi is up for at least K minutes.

All values in input are integers (without leading zeros).

Input

Input is given from Standard Input in the following format:

H_1 M_1 H_2 M_2 K

Output

Print the length of the period in which he can start studying, as an integer.

Sample Input 1

10 0 15 0 30

Sample Output 1

270

Takahashi gets up at exactly ten in the morning and goes to bed at exactly three in the afternoon.
It takes 30 minutes to do the study, so he can start it in the period between ten o'clock and half-past two. The length of this period is 270 minutes, so we should print 270.

Sample Input 2

10 0 12 0 120

Sample Output 2

0

Takahashi gets up at exactly ten in the morning and goes to bed at exactly noon. It takes 120 minutes to do the study, so he has to start it at exactly ten o'clock. Thus, we should print 0.


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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (let* ((h1 (read))
         (m1 (read))
         (h2 (read))
         (m2 (read))
         (k (read)))
    (println (max 0 (- (+ (* h2 60) m2)
                       (+ (* h1 60) m1)
                       k)))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "10 0 15 0 30
"
    "270
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "10 0 12 0 120
"
    "0
")))


(defun main ()
  (let* ((n (read))
         (a (make-array `(,(+ n 2))))
         (b (make-array `(,(1+ n))))
         (m (make-array `(,(1+ n))))
         (2^n 1)
         (ans 0))
    ; memo
    ; (log (expt 10 8) 2) => 26.575424
    ;
    ; read
    (loop :for i :from 0 :to n
          :do (setf (aref a i) (read)))
    ;
    (setf (aref m n) (aref a n))
    (loop :for i :downfrom (1- n) :to 0
          :do (setf (aref m i) (+ (aref a i) (aref m (1+ i)))))
    ; init
    (setf (aref a (1+ n)) 0)
    (when (> (aref a 0) 2^n)
      (format t "-1~%")
      (return-from main))
    (incf ans 2^n)
    (setf (aref b 0) (- 2^n (aref a 0)))
    (setf 2^n (* 2 1))
    ;
    (loop :for i :from 1 :to n
          :do (let* ((p (aref b (1- i)))
                     (c (aref a (1+ i)))
                     (_max (min (* 2 p) 2^n (aref m i)))
                     (_min (ceiling (/ c 2))))
                ;(format t "S: ~A P: ~A A: ~A M: ~A ~A~%" ans p (aref a i) _max _min)
                ; ex. case
                (when (or (> _min _max) (> 0 (- _max (aref a i))))
                  (format t "-1~%")
                  (return-from main))
                ;
                (cond ((= i n)
                       (incf ans (aref a i)))
                      (t
                       (incf ans _max)
                       (setf (aref b i) (- _max (aref a i)))
                       (setf 2^n (* 2 2^n))))))
    (format t "~A~%" ans)))
(main)

Score : 600 points

Problem Statement

Given is an integer sequence of length N+1: A_0, A_1, A_2, \ldots, A_N. Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N, there are exactly A_d leaves at depth d? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1.

Notes

A binary tree is a rooted tree such that each vertex has at most two direct children.

A leaf in a binary tree is a vertex with zero children.

The depth of a vertex v in a binary tree is the distance from the tree's root to v. (The root has the depth of 0.)

The depth of a binary tree is the maximum depth of a vertex in the tree.

Constraints

0 \leq N \leq 10^5

0 \leq A_i \leq 10^{8} (0 \leq i \leq N)

A_N \geq 1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_0 A_1 A_2 \cdots A_N

Output

Print the answer as an integer.

Sample Input 1

3
0 1 1 2

Sample Output 1

7

Below is the tree with the maximum possible number of vertices. It has seven vertices, so we should print 7.

Sample Input 2

4
0 0 1 0 2

Sample Output 2

10

Sample Input 3

2
0 3 1

Sample Output 3

-1

Sample Input 4

1
1 1

Sample Output 4

-1

Sample Input 5

10
0 0 1 1 2 3 5 8 13 21 34

Sample Output 5

264


(defvar ht (make-hash-table :test 'equal))

(defun solve-upper (x A B C D)
  (cond
    ((= x 0) 0)
    (#1=(gethash x ht) #1#)
    (t (setf #1# (min (* x D)
                      (+ C (* D (mod x 5))
                         (solve-upper (floor x 5) A B C D))
                      (+ B (* D (mod x 3))
                         (solve-upper (floor x 3) A B C D))
                      (+ A (* D (mod x 2))
                         (solve-upper (floor x 2) A B C D)))))))

(defun solve-lower (x A B C D)
  (cond
    ((= x 0) 0)
    (#1=(gethash x ht) #1#)
    (t (setf #1# (min (* x D)
                      (+ C (* D (mod (- x) 5))
                         (solve-upper (ceiling x 5) A B C D))
                      (+ B (* D (mod (- x) 3))
                         (solve-upper (ceiling x 3) A B C D))
                      (+ A (* D (mod (- x) 2))
                         (solve-upper (ceiling x 2) A B C D)))))))

(defun solve (N A B C D)
  (let (upper lower)
       (clrhash ht)
       (setf upper (solve-upper N A B C D))
       (clrhash ht)
       (setf lower (solve-lower N A B C D))
       (princ (min lower upper))
       (terpri)))

(loop repeat (read) do
      (solve (read) (read) (read) (read) (read)))

Score : 400 points

Problem Statement

You start with the number 0 and you want to reach the number N.

You can change the number, paying a certain amount of coins, with the following operations:

Multiply the number by 2, paying A coins.

Multiply the number by 3, paying B coins.

Multiply the number by 5, paying C coins.

Increase or decrease the number by 1, paying D coins.

You can perform these operations in arbitrary order and an arbitrary number of times.

What is the minimum number of coins you need to reach N?

You have to solve T testcases.

Constraints

1 \le T \le 10

1 \le N \le 10^{18}

1 \le A, B, C, D \le 10^9

All numbers N, A, B, C, D are integers.

Input

The input is given from Standard Input. The first line of the input is

T

Then, T lines follow describing the T testcases.
Each of the T lines has the format

N A B C D

Output

For each testcase, print the answer on Standard Output followed by a newline.

Sample Input 1

5
11 1 2 4 8
11 1 2 2 8
32 10 8 5 4
29384293847243 454353412 332423423 934923490 1
900000000000000000 332423423 454353412 934923490 987654321

Sample Output 1

20
19
26
3821859835
23441258666

For the first testcase, a sequence of moves that achieves the minimum cost of 20 is:

Initially x = 0.

Pay 8 to increase by 1 (x = 1).

Pay 1 to multiply by 2 (x = 2).

Pay 1 to multiply by 2 (x = 4).

Pay 2 to multiply by 3 (x = 12).

Pay 8 to decrease by 1 (x = 11).

For the second testcase, a sequence of moves that achieves the minimum cost of 19 is:

Initially x = 0.

Pay 8 to increase by 1 (x = 1).

Pay 1 to multiply by 2 (x = 2).

Pay 2 to multiply by 5 (x = 10).

Pay 8 to increase by 1 (x = 11).


(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)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
(declaim (inline shuffle!))
(defun shuffle! (vector &optional (start 0) end)
  "Destructively shuffles VECTOR by Fisher-Yates algorithm."
  (declare (vector vector)
           ((mod #.array-total-size-limit) start)
           ((or null (mod #.array-total-size-limit)) end))
  (loop for i from (- (or end (length vector)) 1) above start
        for j = (+ start (random (- (+ i 1) start)))
        do (rotatef (aref vector i) (aref vector j)))
  vector)

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

(declaim (inline println-matrix))
(defun println-matrix (array &key (separator #\ ) (key #'identity) (writer #'write) (row-start 0) row-end (col-start 0) col-end)
  "Prints a 2-dimensional array."
  (declare ((array * (* *)) array)
           ((integer 0 #.most-positive-fixnum) row-start col-start))
  (let ((row-end (or row-end (array-dimension array 0)))
        (col-end (or col-end (array-dimension array 1))))
    (declare ((integer 0 #.most-positive-fixnum) row-end col-end))
    (loop for i from row-start below row-end
          do (loop for j from col-start below col-end
                   unless (= j col-start)
                   do (princ separator)
                   do (funcall writer (funcall key (aref array i j))))
             (terpri))))

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun test (n seq)
  (let ((mat (make-array (list n n) :element-type 'uint32 :initial-element #xffffffff))
        (plan (make-array (list n n) :element-type 'bit :initial-element 0))
        (res 0))
    (labels ((%get (i j)
               ;; (dbg i j)
               (if (and (<= 0 i (- n 1))
                        (<= 0 j (- n 1)))
                   (aref mat i j)
                   0))
             (decode (p)
               (multiple-value-bind (quot rem) (floor (- p 1) n)
                 (values quot rem))))
      (sb-int:dovector (p (reverse seq))
        (multiple-value-bind (i j) (decode p)
          (setf (aref plan i j) 1))
        (fill (array-storage-vector mat) #xffffffff)
        (dotimes (_ (* n n))
          (dotimes (i n)
            (dotimes (j n)
              (let ((res (min (%get (- i 1) j)
                              (%get (+ i 1) j)
                              (%get i (- j 1))
                              (%get i (+ j 1)))))
                (if (= (aref plan i j) 1)
                    (minf (aref mat i j) (+ res 1))
                    (minf (aref mat i j) res))))))
        (multiple-value-bind (i j) (decode p)
          (setf (aref plan i j) 1)
          (incf res (- (aref mat i j) 1)))
        ;; (println-matrix mat)
        )
      res)))

(defun bench (n sample)
  (loop repeat sample
        do (let ((vec (make-array (* n n) :element-type 'uint31)))
             (dotimes (i (* n n))
               (setf (aref vec i) (+ i 1)))
             (shuffle! vec)
             (assert (= (test n vec) (solve n vec))))))

(defun solve (n ps)
  (declare #.OPT
           (uint16 n)
           ((simple-array uint31 (*)) ps))
  (let* (;; 0-bit: up, 1: down, 2: left, 3: right
         (dists (make-array '(500 500) :element-type 'uint8 :initial-element 0))
         (plan (make-array '(500 500) :element-type 'bit :initial-element 1))
         (que-i (make-array #.(* 500 500) :element-type 'uint16))
         (que-j (make-array #.(* 500 500) :element-type 'uint16))
         (front 0)
         (end 0)
         (res 0))
    (declare (uint16 n)
             (uint32 res front end))
    (dotimes (i (* n n))
      (setf (aref ps i) (- (aref ps i) 1)))
    (dotimes (i n)
      (dotimes (j n)
        (setf (aref dists i j)
              (min (+ i 1) (+ j 1) (- n i) (- n j)))))
    (labels ((enqueue (i j)
               (setf (aref que-i end) i
                     (aref que-j end) j)
               (incf end))
             (queue-reinitialize ()
               (setq front 0 end 0))
             (visit (new-i new-j prev-dist)
               (declare (int32 new-i new-j prev-dist))
               (when (and (<= 0 new-i (- n 1))
                          (<= 0 new-j (- n 1)))
                 (let ((new-dist (+ prev-dist (aref plan new-i new-j))))
                   (when (< new-dist (aref dists new-i new-j))
                     (setf (aref dists new-i new-j) new-dist)
                     (enqueue new-i new-j))))))
      (sb-int:dovector (p ps)
        (queue-reinitialize)
        (multiple-value-bind (i j) (floor p n)
          (decf (aref dists i j))
          (incf res (aref dists i j))
          (setf (aref plan i j) 0)
          (enqueue i j)
          (loop until (= front end)
                do (let* ((i (aref que-i front))
                          (j (aref que-j front))
                          (dist (aref dists i j)))
                     (incf front)
                     (visit (- i 1) j dist)
                     (visit (+ i 1) j dist)
                     (visit i (- j 1) dist)
                     (visit i (+ j 1) dist)))))
      res)))

(defun main ()
  (let* ((n (read))
         (ps (make-array (* n n) :element-type 'uint31 :initial-element 0)))
    (dotimes (i (* n n))
      (setf (aref ps i) (read-fixnum)))
    (println (solve n ps))))

#-swank (main)

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

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

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

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

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

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

#+swank
(defun gen-dat ()
  (uiop:with-output-file (out *dat-pathname* :if-exists :supersede)
    (format out "500~%")
    (let ((vec (make-array (* 500 500))))
      (dotimes (i (* 500 500))
        (setf (aref vec i) (+ i 1)))
      (shuffle! vec)
      (dotimes (i (* 500 500))
        (println (aref vec i) 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 3 7 9 5 4 8 6 2
"
    "1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4
6 7 1 4 13 16 10 9 5 11 12 14 15 2 3 8
"
    "3
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "6
11 21 35 22 7 36 27 34 8 20 15 13 16 1 24 3 2 17 26 9 18 32 31 23 19 14 4 25 10 29 28 33 12 6 5 30
"
    "11
")))

Score : 700 points

Problem Statement

Tonight, in your favourite cinema they are giving the movie Joker and all seats are occupied. In the cinema there are N rows with N seats each, forming an N\times N square. We denote with 1, 2,\dots, N the viewers in the first row (from left to right); with N+1, \dots, 2N the viewers in the second row (from left to right); and so on until the last row, whose viewers are denoted by N^2-N+1,\dots, N^2.

At the end of the movie, the viewers go out of the cinema in a certain order: the i-th viewer leaving her seat is the one denoted by the number P_i. The viewer P_{i+1} waits until viewer P_i has left the cinema before leaving her seat.
To exit from the cinema, a viewer must move from seat to seat until she exits the square of seats (any side of the square is a valid exit). A viewer can move from a seat to one of its 4 adjacent seats (same row or same column).
While leaving the cinema, it might be that a certain viewer x goes through a seat currently occupied by viewer y; in that case viewer y will hate viewer x forever. Each viewer chooses the way that minimizes the number of viewers that will hate her forever.

Compute the number of pairs of viewers (x, y) such that y will hate x forever.

Constraints

2 \le N \le 500

The sequence P_1, P_2, \dots, P_{N^2} is a permutation of \{1, 2, \dots, N^2\}.

Input

The input is given from Standard Input in the format

N
P_1 P_2 \cdots P_{N^2}

Output

If ans is the number of pairs of viewers described in the statement, you should print on Standard Output

ans

Sample Input 1

3
1 3 7 9 5 4 8 6 2

Sample Output 1

1

Before the end of the movie, the viewers are arranged in the cinema as follows:

1 2 3
4 5 6
7 8 9

The first four viewers leaving the cinema (1, 3, 7, 9) can leave the cinema without going through any seat, so they will not be hated by anybody.

Then, viewer 5 must go through one of the seats where viewers 2, 4, 6, 8 are currently seated while leaving the cinema; hence he will be hated by at least one of those viewers.

Finally the remaining viewers can leave the cinema (in the order 4, 8, 6, 2) without going through any occupied seat (actually, they can leave the cinema without going through any seat at all).

Sample Input 2

4
6 7 1 4 13 16 10 9 5 11 12 14 15 2 3 8

Sample Output 2

3

Sample Input 3

6
11 21 35 22 7 36 27 34 8 20 15 13 16 1 24 3 2 17 26 9 18 32 31 23 19 14 4 25 10 29 28 33 12 6 5 30

Sample Output 3

11