struct Item: Equatable {
    var v, w: Int
}
struct Query: Equatable {
    var v, l: Int
}

let n = Int(readLine()!)!
let items = (0..<n).map { _ -> Item in
    let (v, w) = readInts().mapToTuple()
    return Item(v: v, w: w)
}

let q = Int(readLine()!)!
let queries = (0..<q).map { _ -> Query in
    let (v, l) = readInts().mapToTuple()
    return Query(v: v, l: l)
}

for q in queries {
    var x = q.v
    var its = [Item]()
    while x != 0 {
        its.append(items[x - 1])
        x /= 2
    }

    var dp = [[Int]](repeating: [Int](repeating: 0, count: 100_001), count: its.count + 1)
    for i in 0..<its.count {
        for w in 0...q.l {
            if w >= its[i].w {
                dp[i+1][w] = max(dp[i][w-its[i].w] + its[i].v, dp[i][w])
            } else {
                dp[i+1][w] = dp[i][w]
            }
        }
    }
    print(dp[its.count][q.l])
}



func readInts() -> [Int] {
    readLine()!.split(separator: " ").map { Int($0)! }
}

extension Collection {
    func mapToTuple() -> (Element, Element) {
        var i = makeIterator()
        return (i.next()!, i.next()!)
    }
    func mapToTuple() -> (Element, Element, Element) {
        var i = makeIterator()
        return (i.next()!, i.next()!, i.next()!)
    }
    func mapToTuple() -> (Element, Element, Element, Element) {
        var i = makeIterator()
        return (i.next()!, i.next()!, i.next()!, i.next()!)
    }
}

struct DP<Argument: Hashable, Element> {
    var dictionary = [Argument: Element]()

    var expression: (Argument, (Argument) -> Element) -> Element

    init(expression: @escaping (_ argument: Argument, _ note: (Argument) -> Element) -> Element) {
        self.expression = expression
    }

    subscript(_ argument: Argument) -> Element {
        mutating get {
            if let note = dictionary[argument] {
                return note
            } else {
                let result = expression(argument) { self[$0] }
                dictionary[argument] = result
                return result
            }
        }
    }
}
