public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		try {

			int total = in.nextInt();
			if (total <= 0)
				return;
			for (int i = 0; i < total; i++) {
				Node[] tmps = new Node[2];
				tmps[0] = new Node(in.next());
				Node father = getFatherNode(tmps[0]);
				nodeList.remove(father);
				nodeList.add(father);
				tmps[1] = new Node(in.next(), father);
				fill(tmps[1]);
			}

			int totalQuestion = in.nextInt();
			for (int i = 0; i < totalQuestion; i++) {
				Node[] tmps = new Node[2];
				tmps[0] = new Node(in.next());
				tmps[1] = new Node(in.next());
				if (tmps[0].equals(tmps[1])) {
					System.out.println(tmps[0]);
					continue;
				}
				if (!nodeList.contains(tmps[0]) || !nodeList.contains(tmps[1])) {
					System.out.println(-1);
					continue;
				}

				Node node1 = nodeList.get(nodeList.indexOf(tmps[0]));
				markNode(node1, true);
				Node node2 = nodeList.get(nodeList.indexOf(tmps[1]));
				System.out.println(trace(node2));
				unmarkNode(node1);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}