let () = Scanf.scanf "%d\n" @@ fun n ->
  let vws = Array.init n @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun v w -> v, w in
  let dp = Array.make_matrix (min (n + 1) (1 lsl 10)) 100001 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 100000 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
  Scanf.scanf "%d\n" @@ fun q ->
    for i = 0 to q - 1 do
      Scanf.scanf "%d %d\n" @@ fun v l ->
        Printf.printf "%d\n" @@ solve l v
    done

