// Задача "Объявление массивов"
// 9-ая Интернет-олимпиада сезона 2006-2007, базовый уровень
// Автор задачи: Александр Торопов, toropov@rain.ifmo.ru
// Автор решения: Федор Царев, tsarev@rain.ifmo.ru

import java.io.*;
import java.util.*;
import java.math.*;

public class java_ft implements Runnable {

	private Scanner in;
	private PrintWriter out;
	String fname = "java";

	private final BigInteger FOUR = BigInteger.valueOf(4);
	private final BigInteger TWENTY = BigInteger.valueOf(20);

	private void myAssert(boolean e, String message) {
		if (!e) {
			throw new Error("Assertion failure!!! " + message);
		}
	}

	public void solve() {
		int n = in.nextInt();
		myAssert(n >= 1, "n < 1");
		myAssert(n <= 100, "n > 100");

		HashMap<String, Integer> type2size = new HashMap<String, Integer>();

		for (int i = 0; i < n; i++) {
			String name = in.next();
			int size = in.nextInt();
			Integer cur = type2size.get(name);
			myAssert(cur == null, "Type " + name + " duplicated.");
			type2size.put(name, size);
		}

		int m = in.nextInt();
		myAssert(m >= 1, "m < 1");
		myAssert(m <= 1000, "m > 1000");
        
        for (int i = 0; i < m; i++) {
			String curType = in.next();
			
			Integer res = type2size.get(curType);
			myAssert(res != null, "Unknown type: " + curType);

			String size = in.next();
			size = size.replace(";", "");
			size = size.replace("[", " ");
			size = size.replace("]", " ");
			Scanner sc = new Scanner(size);
			sc.next();
			ArrayList<Integer> list = new ArrayList<Integer>();
			while (sc.hasNext()) {
				list.add(sc.nextInt());
			}
			
			BigInteger ans = BigInteger.valueOf(res);

			int cnt = list.size();
			myAssert(cnt >= 1, "cnt < 1");
			myAssert(cnt <= 50, "cnt > 50");
			for (int j = cnt - 1; j >= 0; j--) {
				int curDim = list.get(j);
				myAssert(curDim >= 1, "curDim < 1");
				myAssert(curDim <= 1000, "curDim > 1000");
				ans = ans.multiply(BigInteger.valueOf(curDim));
				ans = ans.add(TWENTY);
				ans = ans.add(FOUR);
			}

			out.println(ans);

        }

	}

	public void run() {
		try {
			solve();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		} finally {
			out.close();
		}		
	}

	public java_ft() {
		try {
			in = new Scanner(new File(fname + ".in"));
			out = new PrintWriter(new File(fname + ".out"));
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}


	public static void main(String[] args) {
		new Thread(new java_ft()).start();
	}

}