#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cstring>
#include <cctype>
#include <complex>
#include <stack>
#include <queue>
#include <unordered_map>
#include <set>
#include <deque>
#include <map>
#include <bitset>
#include <functional>
#include <cmath>

#define INF 1000000000
using namespace std;

template <typename Value, typename Weight = std::uint_fast64_t> class Knapsack {
public:
	using value_type = Value;
	using weight_type = Weight;
	class item_type {
	public:
		value_type v;
		weight_type w;
		item_type(const value_type &v_, const weight_type &w_) : v(v_), w(w_) {}
		bool operator<(const item_type &x) const {
			if (v * x.w == x.v * w)
				return w > x.w;
			return v * x.w > x.v * w;
		}
	};
	using container_type = std::vector<item_type>;
	using size_type = typename container_type::size_type;

private:
	container_type c;
	value_type best;
	std::pair<double, bool> relaxation(size_type i, value_type v_now,
		weight_type residual) {
		double ret = v_now;
		bool f = 1;
		do {
			if (residual == static_cast<weight_type>(0))
				break;
			if (residual >= c[i].w) {
				residual -= c[i].w;
				v_now += c[i].v;
				ret = v_now;
				continue;
			}
			else {
				f = 0;
				ret += static_cast<double>(c[i].v) *
					(static_cast<double>(residual) / c[i].w);
				break;
			}
		} while (++i < size());
		return std::make_pair(ret, f);
	}
	value_type dfs(size_type i, value_type v_now, weight_type residual) {
		if (i == size()) {
			best = std::max(best, v_now);
			return v_now;
		}
		double relax;
		bool f;
		std::tie(relax, f) = relaxation(i, v_now, residual);
		if (f) {
			best = std::max(best, static_cast<value_type>(relax));
			return static_cast<value_type>(relax);
		}
		if (relax < static_cast<double>(best))
			return 0;
		value_type ret = 0;
		if (residual >= c[i].w)
			ret = std::max(ret, dfs(i + 1, v_now + c[i].v, residual - c[i].w));
		ret = std::max(ret, dfs(i + 1, v_now, residual));
		return ret;
	}

public:
	Knapsack() {}
	bool empty() const { return c.empty(); }
	size_type size() const { return c.size(); }
	template <class... Args> void add(Args &&... args) {
		c.emplace_back(std::forward<Args>(args)...);
	}
	void build() { std::sort(c.begin(), c.end()); }
	value_type solve(const weight_type &capacity) {
		best = 0;
		return dfs(0, 0, capacity);
	}
};

int main() {
    ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
	int N;
    cin >> N;

    int vv[N], ww[N];
    int i, Q;
    for(i = 0; i < N; i++){
        int xx, yy;
        cin >> vv[i] >> ww[i];
    }

    int q;
    cin >> q;

    for(Q = 0; Q < q; Q++){
        int V, W;
        cin >> V >> W;
        vector<int> v, w; //ナップサックされる対象
        Knapsack<int, int> K;
        while(V != 0){
            //cout << V << endl;
            K.add(vv[V-1], ww[V-1]);
            V /= 2;
        }

        K.build();
       cout << K.solve(W) << endl;
    }
}
