解法:
本题是bst,无需建树。按前序遍历的顺序检查u,v是否在当前点的左右即可。
int M,N; unordered_set<int> intree; int pre[10002]; int main(){ cin>>M>>N; for(int i=1;i<=N;i++){ cin>>pre[i]; intree.insert(pre[i]); } while(M--){ int u,v; cin>>u>>v; auto f1=intree.find(u); auto f2=intree.find(v); if(f1==intree.end() && f2==intree.end()){ printf("ERROR: %d and %d are not found. ", u,v); }else if(f1==intree.end()){ printf("ERROR: %d is not found. ", u); }else if(f2==intree.end()){ printf("ERROR: %d is not found. ", v); }else { int res=0; for(int i=1;i<=N;i++){ if((u<=pre[i] && v>=pre[i])||(u>=pre[i] && v<=pre[i])){ res=pre[i]; break; } } if(res==u){ printf("%d is an ancestor of %d. ", u,v); }else if(res==v){ printf("%d is an ancestor of %d. ", v,u); }else { printf("LCA of %d and %d is %d. ", u,v,res); } } } return 0; }