open Batteries
let n = read_int ()
let dp = Array.init n @@ fun _ -> [|0; 0|]
let rec vw_loop i =
  if i >= n then () else (
    Scanf.sscanf (read_line()) "%d %d" (fun v w -> 
      dp.(i) <- [|v; w|]
    ); vw_loop (i+1)
  )
let _ = vw_loop 0
let dp2 = Array.init (n+1) @@ fun _ -> []
let rec dp_loop i =
  if i >= n then () else (
    if i = 0 then (dp2.(i) <- dp.(i) :: dp2.(i); dp_loop (i+1)) else (
      dp2.(i) <- dp.(i) :: dp2.(i / 2); dp_loop (i+1)
    )
  )
let _ = dp_loop 0
let q = read_int ()

(* ここからナップザック *)
let nap items l =
(* 価値；重さ*)
  let n_ = Array.length items in
  let nap_dp = Array.init (l+1) @@ fun _ -> 0 in
  for i = 0 to (n_-1) do
    let rec w_loop w =
      if w < 0 then () else (
        if w - items.(i).(1) >= 0 then (
          nap_dp.(w) <- max (nap_dp.(w)) (nap_dp.(w - items.(i).(1)) + items.(i).(0));
          w_loop (w-1)
        ) else w_loop (w-1)
      ) in w_loop l
  done; nap_dp.(l)
  

(* nap [|[|3;2|];[|2;1|];[|6;3|];[|1;2|];[|3;1|];[|85;5|]|] 9;; *)

let rec q_loop i =
  if i >= q then () else (
    Scanf.sscanf (read_line()) "%d %d" (fun v l -> 
      Printf.printf "%d\n" @@ nap (Array.of_list dp2.(v-1)) l
    ); q_loop (i+1)
  )

let _ = q_loop 0