分析
找得到
LCA of 2 and 6 is 3.
8 is an ancestor of 1.
找不到
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
找不到——》任意前序/中序搜索即可
找得到:
LCA of 2 and 6 is 3.
分析中序可知:祖先3必在2,6中间
分析前序可知:祖先3必在2,6前面
因此同时满足上述2点,则说明能找到祖先
当不满足时,则说明情况为8 is an ancestor of 1.
具体实现
实际实现最大问题:题目不会按照 序列的顺序给出
比如2,6是按照序列顺序给的
题目会给6,2
因此问题在于调序——按照序列顺序处理
其次,最后输出时还得按照题目给出顺序进行输出
代码
#include<bits/stdc++.h>
using namespace std;
int pairs, quantity, x, y;
vector<int>preorder, inorder;
map<int, int>pre_id, in_id;
void Judge(map<int, int>::iterator, map<int, int>::iterator, int, int);
void AdjustOrder(map<int, int>::iterator&, map<int, int>::iterator&);
int main() {
scanf("%d %d", &pairs, &quantity);
inorder.resize(quantity);
for (int i = 0; i < quantity; i++) {
scanf("%d", &x);
inorder[i] = x;
in_id[x] = i;
}
preorder.resize(quantity);
for (int i = 0; i < quantity; i++) {
scanf("%d", &x);
preorder[i] = x;
pre_id[x] = i;
}
for (int i = 0; i < pairs; i++) {
scanf("%d %d", &x, &y);
auto x_pre_id = pre_id.find(x);
auto y_pre_id = pre_id.find(y);
if (x_pre_id == pre_id.end() || y_pre_id == pre_id.end()) {
if (x_pre_id == pre_id.end() && y_pre_id == pre_id.end()) {
printf("ERROR: %d and %d are not found.\n",x,y);
continue;
}
printf("ERROR: %d is not found.\n", x_pre_id == pre_id.end() ? x : y);
continue;
}
auto x_in_id = in_id.find(x);
auto y_in_id = in_id.find(y);
AdjustOrder(x_in_id, y_in_id);
AdjustOrder(x_pre_id, y_pre_id);
Judge(x_pre_id, y_pre_id, x_in_id->second, y_in_id->second);
}
return 0;
}
void Judge(map<int, int>::iterator front, map<int, int>::iterator back,int in_front,int in_back) {
if (in_front + 1 != in_back) {
for (int i = 0; i < front->second; i++) {
auto j = in_id.find(preorder[i]);
if ( j->second <in_back && j->second>in_front) {
printf("LCA of %d and %d is %d.\n", x, y, j->first);
return;
}
}
}
printf("%d is an ancestor of %d.\n", front->first, back->first);
}
void AdjustOrder(map<int, int>::iterator& x, map<int, int>::iterator& y) {
if (x->second > y->second) {
swap(x, y);
}
}