A1151
Description:
给出中序和后序序列,求两个节点的最近公共祖先;
算法描述:
- 如果两个节点位于根节点的两侧,则该根节点即为最近公共祖先;
- 若两个节点均位于根节点单侧,则递归遍历该子树;
- C++ vector类resize方法,为vector分配内存大小
aVector.resize(int n,element) //n为欲分配的单元数量,element可省略,为欲填充的数值;
- 思考要比动手重要,复杂不说,健壮性也不好,再次膜拜柳神的代码;
- 柳神传送门;
#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>getIn; //数值-先序序列下标的映射
vector<int>in, pre;
int m, n;
//inL:中序序列左界,inR:中序序列右界,preRoot:根节点的后序序列下标,uv:欲查找的结点值
void lca(int inL, int inR, int preRoot, int u, int v){
if(inL > inR) return ;
int inRoot = getIn[pre[preRoot]], uIn = getIn[u], vIn = getIn[v];
if(uIn < inRoot && vIn < inRoot) //单侧,递归
lca(inL, inRoot-1, preRoot+1, u, v);
else if(uIn > inRoot && vIn > inRoot) //单侧,递归
lca(inRoot+1, inR, preRoot+1, u, v);
else if(uIn == inRoot) //u节点为根节点
printf("%d is an ancestor of %d.\n", u, v);
else if(vIn == inRoot) //v节点为根节点
printf("%d is an ancestor of %d.\n", v, u);
else if((uIn<inRoot&&vIn>inRoot)||(uIn>inRoot&&vIn<inRoot)) //在两侧,当前根节点即为LCA
printf("LCA of %d and %d is %d.\n", u, v, in[inRoot]);
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
scanf("%d%d", &m, &n);
in.resize(n+1), pre.resize(n+1); //初始化vector大小,下标起始为1所以大小为n+1
for(int i = 1; i <= n; i++){
scanf("%d", &in[i]);
getIn.insert(make_pair(in[i], i)); //添加映射
}
for(int i = 1; i <= n; i++)
scanf("%d", &pre[i]);
int u, v;
for(int i = 0; i < m; i++){
scanf("%d%d", &u, &v);
if(getIn.count(u)==0&&getIn.count(v)==0)
printf("ERROR: %d and %d are not found.\n", u, v);
else if(getIn.count(u)==0||getIn.count(v)==0)
printf("ERROR: %d is not found.\n", getIn.count(u)==0?u:v);
else
lca(1, n, 1, u, v);
}
return 0;
}