int N = vec.size(); for (int i = 0; i < N; i++) names[vec[i]->name] = i;
int p = -1; int n = N; while (n > 0) { n >>= 1; p++; } for (int i = 0; i < N; i++) M[i][0] = vec[i]; for (int i = 1; i <= p; i++) { for (int j = 0; j < N; j++) { if (j + (1 << i - 1) < N) M[j][i] = M[j][i - 1]->level < M[j + (1 << i - 1)][i - 1]->level ? M[j][i - 1] : M[j + (1 << i - 1)][i - 1]; else M[j][i] = M[j][i - 1]; } } }
string find(string a, string b){ int l = names[a], r = names[b]; if (l > r) { int tmp = l; l = r; r = tmp; } int p = -1; int n = r - l + 1; while (n > 0) { n >>= 1; p++; } Node* ancestor = M[l][p]->level < M[r - (1 << p) + 1][p]->level ? M[l][p] : M[r - (1 << p) + 1][p]; return ancestor->name; }
intmain(){ int N = 0, M = 0; cin >> N; unordered_map<string, Node*> family; string father, son; cin >> father >> son; Node* root = newNode(father); root->level = 0; family[son] = newNode(son); root->children.push_back(family[son]); family[father] = root; for (int i = 1; i < N; i++) { cin >> father >> son; if (family.find(father) == family.end()) family[father] = newNode(father); family[son] = newNode(son); family[father]->children.push_back(family[son]); }
rmqSt(root);
cin >> M; for (int i = 0; i < M; i++) { string a, b; cin >> a >> b; cout << find(a, b) << endl; }
for (auto it = family.begin(); it != family.end(); it++) delete it->second;