题意很简单,给出一颗二叉搜索树,求两个节点的最近公共祖先
标记是否出现时能用map就用map,用数组会出段错误和答案错误的问题
还有就是,精简代码
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e4+100;
int nodes[maxn];
map<int,int>vis;
int main(){
int u,v,n,m;
cin>>m>>n;
for(int i=0;i<n;i++){
cin>>nodes[i];
vis[nodes[i]]=1;
}
while(m--){
int a;
cin>>u>>v;
for(int i=0;i<n;i++){
a=nodes[i];
if(nodes[i]>=u&&nodes[i]<=v||nodes[i]>=v&&nodes[i]<=u){
break;
}
}
if(!vis[u]&&!vis[v]) printf("ERROR: %d and %d are not found.\n",u,v);
else if(!vis[u]||!vis[v]) printf("ERROR: %d is not found.\n",!vis[u]?u:v);
else if(a==u||a==v) printf("%d is an ancestor of %d.\n",a==u?u:v,a==u?v:u);
else printf("LCA of %d and %d is %d.\n",u,v,a);
}
return 0;
}