let () = Scanf.scanf "%d\n" @@ fun n ->
  let vws = Array.init n @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun v w -> v, w in
  Scanf.scanf "%d\n" @@ fun q ->
    let vls = Array.init q @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun v l -> v, l in
    let maxl = Array.fold_right (fun (_, l) -> max l) vls min_int in
    let dp = Array.make_matrix (min (n + 1) (1 lsl 10)) (maxl + 1) 0 in
    for i = 1 to min n ((1 lsl 10) - 1) do
      let v, w = vws.(i - 1) in
      for j = 0 to w - 1 do
        dp.(i).(j) <- dp.(i / 2).(j)
      done;
      for j = w to maxl do
        dp.(i).(j) <- max dp.(i / 2).(j) (v + dp.(i / 2).(j - w))
      done
    done;
    let rec solve l i =
      let v, w = vws.(i - 1) in
      if l < 0
      then min_int
      else if i < 1 lsl 10
      then dp.(i).(l)
      else max (solve l (i / 2)) (v + solve (l - w) (i / 2)) in
    Array.iter (fun (v, l) -> Printf.printf "%d\n" @@ solve l v) vls

