#include<iostream>
#include<cmath>
#include<algorithm>
#include<iomanip>
#include<climits>
#include<numeric>
#include<set>
#include<sstream>
#include<map>
#include<vector>
#include<string>
#include<regex>

using namespace std;

const long long MOD = (long long)(1e9 + 7);

vector<string> split(const string& haystack, const string& needle) {
	vector<string> result;
	size_t start_pos = 0;
	size_t found_pos = haystack.find(needle, start_pos);
	while (found_pos != string::npos) {
		size_t count = found_pos - start_pos;
		string token = haystack.substr(start_pos, count);
		if (!token.empty()) {
			result.push_back(token);
		}
		start_pos = found_pos + needle.length();
		found_pos = haystack.find(needle, start_pos);
	}

	string last_token = haystack.substr(start_pos);
	if (!last_token.empty()) {
		result.push_back(last_token);
	}
	return result;
}

int main() {
	map<string, int> mp;
	for (int i = 0;i < 10;i++) {
		string name;cin >> name;
		int mass;cin >> mass;
		mp[name] = mass;
	}
	regex pattern("([A-Z][a-z]*)(\\d*)");
	int t;cin >> t;
	for (int i = 1;i <= t;i++) {
		string s;cin >> s;
		long long sum = 0;
		for (sregex_iterator it(s.begin(), s.end(), pattern);it != sregex_iterator();it++) {
			string element = (*it)[1];
			string mass = (*it)[2];
			int count = (mass.empty()) ? 1 : stoi(mass);
			sum = sum + count * mp[element];
		}
		cout << sum << endl;
	}
	return 0;
}

