Sample Input:
6 8
7 2 3 4 6 5 1 8
5 3 7 2 6 4 8 1
2 6
8 1
7 9
12 -3
0 8
99 99
Sample Output:
LCA of 2 and 6 is 3.
8 is an ancestor of 1.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.
题解:
根据先序遍历,根左右;
以及中序遍历,左根右,
对于给定的u,v,只要确定u,v都在中序遍历中(包括u,v两个端点),那么他们的根一定是在中序遍历[u,v]中,假设i是[u,v]中的点,只要找到在先序遍历中下标最小的i,就可以确定他们的公共根
#include <iostream>
#include <map>
#include <vector>
#include <unordered_map>
using namespace std;
int n,m;
vector<int> in,pre;
map<int,int> pre_index_in;
int main(){
cin >> n >> m;
int temp;
in.resize(m);
pre.resize(m);
for(int i=0;i<m;i++){
scanf_s("%d",&in[i]);
pre_index_in[in[i]] = i;
}
for(int i=0;i<m;i++){
scanf_s("%d",&pre[i]);
}
for(int i=0;i<n;i++){
int a,b;
cin >> a >> b;
int j,k;
for(j=0;j<m;j++){
if(in[j] == a) break;;
}
for(k=0;k<m;k++){
if(in[k] == b) break;;
}
if(j >= m && k >= m ){
printf("ERROR: %d and %d are not found.\n",a,b);
}
else if(j>=m){
printf("ERROR: %d is not found.\n",a);
}
else if( k>=m ){
printf("ERROR: %d is not found.\n",b);
}
else{
int min_index;
int post_i;
for(min_index=0;min_index<m;min_index++){
post_i = pre_index_in[pre[min_index]];
if(post_i >= min(j,k) && post_i <= max(j,k)){
break;
}
}
if(post_i == j){
printf("%d is an ancestor of %d.\n",a,b);
}
else if(post_i == k ){
printf("%d is an ancestor of %d.\n",b,a);
}
else{
printf("LCA of %d and %d is %d.\n",a,b,pre[min_index]);
}
}
}
system("pause");
return 0;
}