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


Measured memory_bytes: 91320