string lowestComAnc(unordered_map<string, Node*> nodes, string a, string b){ if (a == b) return a; if (nodes.find(a) == nodes.end() || nodes.find(b) == nodes.end()) return"-1";
for (auto it = nodes.begin(); it != nodes.end(); it++) it->second->visited = false;
Node *A = nodes[a], *B = nodes[b]; while (A) { A->visited = true; A = A->ancestor; }
while (B) { if (B->visited) return B->name; B = B->ancestor; }
return"-1"; }
intmain(){ int N = 0, M = 0; cin >> N; unordered_map<string, Node*> nodes; for (int i = 0; i < N; i++) { string father, son; cin >> father >> son; Node* node = newNode(son); if (nodes.find(father) == nodes.end()) nodes.insert(make_pair(father, newNode(father))); node->ancestor = nodes[father]; nodes.insert(make_pair(son, node)); } cin >> M; for (int i = 0; i < M; i++) { string a, b; cin >> a >> b; cout << lowestComAnc(nodes, a, b) << endl; }