import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;

public class squirell_ak {

	HashMap<String, HashSet<Integer>> bad = new HashMap<String, HashSet<Integer>>();
	HashMap<String, Integer> num = new HashMap<String, Integer>();

	void solve() throws IOException {
		int n = Integer.parseInt(br.readLine());
		for (int i = 0; i < n; i++) {
			String now = br.readLine();
			int pos;
			for (pos = 0; pos < now.length()
					&& Character.isLowerCase(now.charAt(pos)); pos++)
				;
			String s = now.substring(0, pos);
			int num = Integer.parseInt(now.substring(pos, now.length()));
			if (!bad.containsKey(s)) {
				bad.put(s, new HashSet<Integer>());
			}
			bad.get(s).add(num);
		}
		int m = Integer.parseInt(br.readLine());
		for (int i = 0; i < m; i++) {
			String name = br.readLine();
			if (!num.containsKey(name)) {
				num.put(name, 0);
			}
			int ans = num.get(name) + 1;
			while (true) {
				if (!bad.containsKey(name) || !bad.get(name).contains(ans)) {
					break;
				}
				ans++;
			}
			num.put(name, ans);
			out.println(ans);
		}
	}

	PrintWriter out;
	BufferedReader br;

	void run() throws IOException {
		br = new BufferedReader(new FileReader(new File("squirell.in")));
		out = new PrintWriter("squirell.out");
		solve();
		out.close();
	}

	public static void main(String[] args) throws IOException {
		new squirell_ak().run();
	}
}
