#include<iostream>#include<vector>usingnamespace std;constint maxn =10000010;bool exist[maxn]={false};//BST的结点定义struct node{int data;
node *lchild,*rchild;};//BST的插入函数,用于建立BSTvoidinsert(node*&root,int x){if(root ==NULL){
root =new node;
root->data = x;
root->lchild =NULL;
root->rchild =NULL;return;}if(root->data > x){insert(root->lchild, x);}else{insert(root->rchild, x);}}//BST查找结点,记录路径,在两个路径中寻找最后一个相同结点,就是他们的最近共同祖先
vector<int> path;voidsearch(node* root,int x){
path.push_back(root->data);if(root->data == x){return;}elseif(root->data > x){search(root->lchild, x);}elsesearch(root->rchild, x);}intmain(){int m, n;scanf("%d%d",&m,&n);
node* root =NULL;for(int i =0; i < n; i++){int x;scanf("%d",&x);
exist[x]=true;insert(root, x);}for(int i =0; i < m; i++){int a, b;scanf("%d%d",&a,&b);if(!exist[a]&&!exist[b]){printf("ERROR: %d and %d are not found.\n", a, b);}elseif(!exist[a]){printf("ERROR: %d is not found.\n", a);}elseif(!exist[b]){printf("ERROR: %d is not found.\n", b);}else{
vector<int> path1, path2;
path.clear();search(root, a);
path1 = path;
path.clear();search(root, b);
path2 = path;int j =0, k =0;int ans;while(j < path1.size()&& k < path2.size()){if(path1[j]== path2[k])
ans = path1[j];elsebreak;
j++;
k++;}if(ans == a){printf("%d is an ancestor of %d.\n", a, b);}elseif(ans == b){printf("%d is an ancestor of %d.\n", b, a);}else{printf("LCA of %d and %d is %d.\n", a, b, ans);}}}return0;}
#include<iostream>#include<map>usingnamespace std;constint maxn =10010;
map<int,bool> mp;int pre[maxn];intmain(){int m, n;
cin >> m >> n;for(int i =0; i < n; i++){scanf("%d",&pre[i]);
mp[pre[i]]=true;}for(int i =0; i < m; i++){int a, b;scanf("%d%d",&a,&b);if(mp[a]==false&& mp[b]==false){printf("ERROR: %d and %d are not found.\n", a, b);}elseif(mp[a]==false|| mp[b]==false){printf("ERROR: %d is not found.\n", mp[a]==false? a : b);}else{int ans;for(int j =0; j < n; j++){
ans = pre[j];if((ans >= a && ans <= b)||(ans >= b && ans <= a))break;}if(ans == a || ans == b){printf("%d is an ancestor of %d.\n", ans, ans == a ? b : a);}else{printf("LCA of %d and %d is %d.\n", a, b, ans);}}}return0;}