#include <bits/stdc++.h>
using namespace std;
map<string,int> nameMap;
string names[100005];
struct node{
int pa;
vector<int> son;
vector<pair<int,int> > qu;
node() : pa(-1){}
}no[100005];
int ans[100005];
int findset(int x){
if(x != no[x].pa)
no[x].pa = findset(no[x].pa);
return no[x].pa;
}
void dfs(int f){
no[f].pa = f;
int len = no[f].son.size();
for(int i=0 ;i<len;i++){
int index = no[f].son[i];
dfs(index);
no[index].pa = f;
}
int qlen = no[f].qu.size();
for(int i=0; i<qlen; i++){
pair<int, int> p = no[f].qu[i];
if(no[p.first].pa != -1)
ans[p.second] = findset(p.first);
}
}
int main(){
int N,M;
scanf("%d",&N);
for(int i=0; i<N; i++){
string fa,son;
cin>>fa>>son;
if(nameMap.find(fa) == nameMap.end())
nameMap[fa] = nameMap.size();
if(nameMap.find(son) == nameMap.end())
nameMap[son] = nameMap.size();
int nf = nameMap[fa], ns = nameMap[son];
names[nf] = fa;
names[ns] = son;
no[nf].son.push_back(ns);
}
scanf("%d",&M);
for(int i=0; i<M; i++){
string qu1,qu2;
cin>>qu1>>qu2;
int n1 = nameMap[qu1], n2 = nameMap[qu2];
no[n1].qu.push_back(make_pair(n2,i));
no[n2].qu.push_back(make_pair(n1,i));
}
dfs(1);
for(int i = 0; i < M ; i++)
//puts(names[ans[i]].c_str());
cout<<names[ans[i]]<<endl;
return 0;
}