分析
本题需要理清楚一些基础概念:LCA、BST、前序遍历
本题的判断可分为2类:
能找到:
8 is an ancestor of 7.
LCA of 2 and 5 is 3.
找不到:
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
进一步分析:能找到
LCA of 2 and 5 is 3.即意味 2和5前面存在一个数,介于2、5之间
(BST和前序的特点决定)
8 is an ancestor of 7.即意味不存在这个数
其他注意事项
LCA of 2 and 5 is 3. 应按照题目给出的顺序进行输出,即2、5;你不能5,2输出
代码
#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()) {
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]);
return;
}
}
printf("%d is an ancestor of %d.\n", front->first, back->first);
}
本文详细解析了一道涉及LCA(最近公共祖先)和BST(二叉搜索树)的算法题,通过分析题目需求,讲解了如何利用前序遍历的特性解决LCA查找和祖先判断的问题,并提供了完整的C++代码实现。
2848

被折叠的 条评论
为什么被折叠?



