分析
基础理论:
前序的特点:根左右
中序的特点:左根右
结论:(有)祖先一定同时同时出现在
········前序的左点前·········
·····中序的左右点中间······
具体分析:
序号0 1 2 3 4 5 6 7
前序5 3 7 2 6 4 8 1
中序7 2 3 4 6 5 1 8
- 例:2 6
前序祖先范围为 5 3 7 2
中序祖先范围为 2 3 4 6
其中同时出现的仅有3 - 例:2 1
前序祖先范围为 5 3 7 2 6 4 8 1
中序祖先范围为 2 3 4 6 5 1
其中同时出现的有5 3
同时出现时,仅需抓前序中第一个匹配的,即5
注:以上成立是保证给的是2 1,即顺序
······实际给出的有可能是1 2,则需要调序
具体实现
- 注意题目先给的是中序
- 用map保存值和序号
- 由于需要2次调整顺序,用一个函数进行调序
- 在进行匹配时,取出前序的元素,用for
而是否在中序中匹配,不可用for(会超时)——》用map进行搜索,判断搜出来值在 给定值中间
5.当然还有就是按照题目给的x,y顺序输出“8 is an ancestor of 1.”
代码
#include<bits/stdc++.h>
using namespace std;
int pairs{ 0 }, quantity{ 0 }, 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);
}
}