#include <bits/stdc++.h>
using namespace std;

int n;
int64_t v[1 << 18], w[1 << 18];
int64_t val[1 << 9][100010];

int main() {
	cin >> n;
	for(int i = 0; i < n; ++i) {
		cin >> v[i] >> w[i];
	}
	for(int i = 1; i < (1 << 9); ++i) {
		for(int j = 0; j < 100010; ++j) {
			val[i][j] = val[i / 2][j];
			if(j - 1 >= 0) val[i][j] = max(val[i][j], val[i][j - 1]);
			if(j - w[i - 1] >= 0) {
				val[i][j] = max(val[i][j], val[i / 2][j - w[i - 1]] + v[i - 1]);
			}
		}
	}
	int q; cin >> q;
	while(q--) {
		int vv, l; cin >> vv >> l;
		if(vv < (1 << 9)) {
			cout << val[vv][l] << '\n';
			continue;
		}
		vector<int> vec;
		while(vv >= (1 << 9)) {
			vec.push_back(vv - 1);
			vv >>= 1;
		}
		int64_t ans = 0;
		int vn = vec.size();
		for(int mask = 0; mask < (1 << vn); ++mask) {
			int64_t W = 0;
			int64_t V = 0;
			for(int i = 0; i < vn; ++i) {
				if(mask >> i & 1) {
					W += w[vec[i]];
					V += v[vec[i]];
				}
			}
			if(l - W >= 0) {
				ans = max(ans, val[vv][l - W] + V);
			}
		}
		cout << ans << '\n';
	}
	return 0;
}