1143 Lowest Common Ancestor
解法:
本题是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.\n", u,v); }else if(f1==intree.end()){ printf("ERROR: %d is not found.\n", u); }else if(f2==intree.end()){ printf("ERROR: %d is not found.\n", 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.\n", u,v); }else if(res==v){ printf("%d is an ancestor of %d.\n", v,u); }else { printf("LCA of %d and %d is %d.\n", u,v,res); } } } return 0; }