cost = {}
places = set()

def update(begin, end, cents):
    places.add(begin)
    places.add(end)
    if (begin,end) not in cost:
        cost[(begin,end)] = cents
        cost[(end,begin)] = cents
    else:
        if cost[begin,end] > cents:
            cost[(begin,end)] = cents
            cost[(end,begin)] = cents
            

def neighbors(point):
    return set(begin for (begin,end) in cost.keys() if end == point)

def shortest(costs, finished):
    keys = []
    for (key,value) in costs.items():
        if key not in finished:
            if value != None:
                keys.append((key,value))
    #keys = [(key,value) for (key,value) in costs.items() if (key not in finished) and (value != None)]
    keys.sort(key=lambda x:x[1])
    return keys[0][0]

def dykstra(begin, end):
    finished = set()
    costs = {}
    for dest in places:
        costs[dest] = None
    costs[begin] = 0
    while end not in finished:
        current = shortest(costs, finished)
        for point in neighbors(current):
            if point not in finished:
                if  (costs[point] == None) or (costs[point] > costs[current] + cost[(current,point)]):
                    costs[point] = costs[current] + cost[(current,point)]
        finished.add(current)
    return costs[end]

for _ in range(4):
    for _ in range(int(input())):
        line = input()
        start = line.split()[0]
        destinations = line[len(start)+2:-1].split(")(")
        for destination in destinations:
            stop, cents = destination.split()
            update(start, stop, int(cents))
for _ in range(int(input())):
    stops = input().split()
    previous = stops[0]
    total = 0
    for stop in stops[1:]:
        total = total + dykstra(previous, stop)
        previous = stop
    print(total)
        
        
