Problem:
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

Solution in Common Lisp (SBCL 2.0.3) (judge verdict: Time Limit Exceeded)

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