#include <iostream>
#include <unordered_map>
#include <unordered_set>
using namespace std;
unordered_map<int,int> posInInOrder;
unordered_set<int> nodes;
int preOrder[10010];
int main(){
int m,n;
scanf("%d%d",&m,&n);
for(int i = 0;i < n;i++){ // inorder
int temp;
scanf("%d",&temp);
posInInOrder[temp] = i;
nodes.insert(temp);
}
for(int i = 0;i < n;i++){ // preorder
scanf("%d",&preOrder[i]);
}
for(int i = 0;i < m;i++){
int u,v;
scanf("%d%d",&u,&v);
bool hasl = true,hasr = true;
if(nodes.find(u) == nodes.end())
hasl = false;
if(nodes.find(v) == nodes.end())
hasr = false;
if(hasl == false && hasr == false){
printf("ERROR: %d and %d are not found.\n",u,v);
}else if(hasl == false){
printf("ERROR: %d is not found.\n",u);
}else if(hasr == false){
printf("ERROR: %d is not found.\n",v);
}else{
for(int j = 0;j < n;j++){
if(preOrder[j] == u){
printf("%d is an ancestor of %d.\n",u,v);
break;
}else if(preOrder[j] == v){
printf("%d is an ancestor of %d.\n",v,u);
break;
}else if((posInInOrder[preOrder[j]] < posInInOrder[u] && posInInOrder[preOrder[j]] > posInInOrder[v]) || (posInInOrder[preOrder[j]] > posInInOrder[u] && posInInOrder[preOrder[j]] < posInInOrder[v])){
printf("LCA of %d and %d is %d.\n",u,v,preOrder[j]);
break;
}
}
}
}
system("pause");
return 0;
}
PAT | A1151 LCA in a Binary Tree
最新推荐文章于 2024-07-25 14:57:29 发布