A1143
Description:
给出二叉排序树的先序序列,求任意两节点的最近公共祖先;
算法描述:
- 二叉排序树中序序列特性即是递增序列,将先序序列排序即可得中序序列;
- 如果两个节点位于根节点的两侧,则该根节点即为最近公共祖先;
- 若两个节点均位于根节点单侧,则递归遍历该子树;
- 注意映射关系不要写错了,比如代码中第17行获取先序序列下标是用mp映射,第一遍写的时候写成了in[pre[preRoot]]…
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<unordered_map>
#include<vector>
#include<queue>
using namespace std;
unordered_map<int,int>mp; //数值-in下标映射
vector<int>pre, in;
int n, m, u, v;
void lca(int inL, int inR, int preRoot){
if(inL > inR) return ;
int inRoot = mp[pre[preRoot]];
if(u<pre[preRoot]&&v<pre[preRoot])
lca(inL, inRoot-1, preRoot+1);
else if(u>pre[preRoot]&&v>pre[preRoot])
lca(inRoot+1, inR, preRoot+1);
else if(u == pre[preRoot])
printf("%d is an ancestor of %d.\n", u, v);
else if(v == pre[preRoot])
printf("%d is an ancestor of %d.\n", v, u);
else if((u<pre[preRoot]&&v>pre[preRoot])||(u>pre[preRoot]&&v<pre[preRoot]))
printf("LCA of %d and %d is %d.\n", u, v, pre[preRoot]);
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
scanf("%d%d", &m, &n);
pre.resize(n+1), in.resize(n+1);
for(int i = 1; i <= n; i++){
scanf("%d", &pre[i]);
in[i] = pre[i];
}
sort(in.begin()+1, in.end());
for(int i = 1; i <= n; i++){
mp.insert(make_pair(in[i], i));
}
for(int i = 1; i <= m; i++){
scanf("%d%d", &u, &v);
if(mp.count(u)==0&&mp.count(v)==0)
printf("ERROR: %d and %d are not found.\n", u, v);
else if((mp.count(u)!=0&&mp.count(v)==0)||(mp.count(u)==0&&mp.count(v)!=0))
printf("ERROR: %d is not found.\n", mp.count(u)==0?u:v);
else
lca(1, n, 1);
}
return 0;
}