题意:LCA入门题目 = =
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <string>
#include <cstring>
#include <vector>
#include <list>
#include <queue>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
using namespace std;
#define rep(i, s, t) for(int (i)=(s);(i)<=(t);++(i))
#define urep(i, s, t) for(int (i)=(s);(i)>=(t);--(i))
typedef long long LL;
const int inf = 0x7fffffff;
const int Maxn = (int)1e5;
struct Query {
int v;
int time;
};
map<string, int> id;
vector<string> name;
int tot = 0;
vector<int> g[Maxn+5];
vector<Query> query[Maxn+5];
int mark[Maxn+5];
int fa[Maxn+5];
int Rank[Maxn+5];
int ancestor[Maxn+5];
int ans[Maxn+5];
int Find(int u) {
return u == fa[u] ? u : fa[u] = Find(fa[u]);
}
void Union(int x, int y) {
int xRoot = Find(x), yRoot = Find(y);
if (xRoot == yRoot) return;
if (Rank[xRoot] >= Rank[yRoot]) {
fa[yRoot] = xRoot;
Rank[xRoot] += Rank[yRoot];
}
else {
fa[xRoot] = yRoot;
Rank[yRoot] += Rank[xRoot];
}
}
void TarjanOLCA(int u) {
fa[u] = u;
Rank[u] = 1;
ancestor[u] = u;
int sz = g[u].size();
int v;
rep(i, 0, sz-1) {
v = g[u][i];
TarjanOLCA(v);
Union(u, v);
ancestor[Find(u)] = u;
}
mark[u] = 1;
sz = query[u].size();
rep(i, 0, sz-1) {
Query& q = query[u][i];
if (mark[q.v] == 1) {
ans[q.time] = ancestor[Find(q.v)];
}
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.in", "r", stdin);
#endif
iostream::sync_with_stdio(false);
int n, m;
cin >> n;
string father_i, son_i;
rep(i, 1, n) {
cin >> father_i >> son_i;
if (id.count(father_i) == 0) {
id[father_i] = tot++;
name.push_back(father_i);
}
if (id.count(son_i) == 0) {
id[son_i] = tot++;
name.push_back(son_i);
}
int fa_id = id[father_i], son_id = id[son_i];
g[fa_id].push_back(son_id);
}
cin >> m;
string x, y;
int u, v;
int cnt = 0;
rep(i, 1, m) {
cin >> x >> y;
u = id[x];
v = id[y];
//cout << "read: " << x << ' ' << y << " id: " << u << ' ' << v << endl;
query[u].push_back((Query){v, cnt});
query[v].push_back((Query){u, cnt++});
}
TarjanOLCA(0);
rep(i, 0, m-1) cout << name[ans[i]] << '\n';
return 0;
}