分析
基础理论:
前序的特点:根左右
而排序树 父结点的值一定在 任意左右子树值的中间
具体分析:
序号0 1 2 3 4 5 6 7
前序6 3 1 2 5 4 8 7
2 5
-
若能在给的点(最靠前的点)前面 找到一个值在 给的值中间
那么一定是ACL
即假如给的是5 2,则最靠前的是2 ,序号3 ;
则在序号0——3中找一个值x 符合 2<x<5
6 3 1 2 ——》根为 3 -
如果找不到呢?
例如8 7
则序号最前的是父结点
比如给出的若是 7 8
其中7序号为7,8序号为6
则8序号小,为父结点
具体实现
- 用map保存序号
- 通过三目运算符来判断 哪个没找到/按照顺序传递x,y
- 注意输出“LCA of x and y is 3.”中按照题目给的x,y顺序进行输出,而不是排过序的;否则有测试点报错
代码
#include<bits/stdc++.h>
using namespace std;
int pairs{ 0 }, quantity{ 0 }, x, y;
map<int, int>id;//值——下标
vector<int>bst;
void Judge(map<int, int>::iterator, map<int, int>::iterator);
int main() {
scanf("%d %d", &pairs, &quantity);
bst.resize(quantity);
for (int i = 0; i < quantity; i++) {
scanf("%d", &x);
bst[i] = x;
id[x] = i;
}
map<int, int>::iterator xid, yid;
for (int i = 0; i < pairs; i++) {
scanf("%d %d", &x, &y);
xid = id.find(x);
yid = id.find(y);
if (xid == id.end() || yid == id.end()) {//用一句话合并掉2次类似判定 // 避免特地写个函数 或是写3给if
if (xid == id.end() && yid == id.end()) {
printf("ERROR: %d and %d are not found.\n", x, y);
continue;
}
printf("ERROR: %d is not found.\n", xid == id.end() ? x : y);
continue;
}
xid->second > yid->second ? Judge(yid, xid) : Judge(xid, yid);
}
return 0;
}
void Judge(map<int, int>::iterator front, map<int, int>::iterator back) {
for (int i = 0; i != front->second; i++) {
if (bst[i] > front->first && bst[i] < back->first) {
printf("LCA of %d and %d is %d.\n", x, y, bst[i]);//注意要按照题目给的xy顺序输出,而不是front->first, back->first
return;
}
}
printf("%d is an ancestor of %d.\n", front->first, back->first);
}