题意
找他的最近公共祖先结点。。听着名字就被糊弄过去了
其实这是道很简单的题,因为他是BST啊!
左边的树比根节点小,右边的树比根节点大,那么就是循环一下数组,看一下有没有满足比x结点大,比y结点小的这么一个点 或者(比x小,比y大)
主要最近在学LCA类的算法。。。就直接做了,完全没想到BST的特点。。。
对code2解法感兴趣的可以去👉这里👈看看
code 1
#include <bits/stdc++.h>
using namespace std;
int pre[10010];
map<int,int> judge;
int main(){
int n,m,x,y;
cin>>n>>m;
for(int i=0;i<m;i++){
cin>>pre[i];
judge[pre[i]]=1;
}
for(int i=0;i<n;i++){
cin>>x>>y;
int j=0;
for(;j<m;j++) if((x>=pre[j]&&y<=pre[j])||(x<=pre[j]&&y>=pre[j])) break;
if (!judge[x]&&!judge[y])
printf("ERROR: %d and %d are not found.\n",x,y);
else if (!judge[x]||!judge[y])
printf("ERROR: %d is not found.\n", judge[x]?y:x);
else if (pre[j]==x||pre[j]==y)
printf("%d is an ancestor of %d.\n",pre[j],pre[j]==x?y:x);
else printf("LCA of %d and %d is %d.\n",x,y,pre[j]);
}
}
code 2
注释是bug,,,因为我。经常会出写错,,,鹅且找半天
//int[st]=pre[root]
#include <bits/stdc++.h>
using namespace std;
int k,n,x,y;
const int maxn=1000100;
vector<int> parent(2*maxn),depth(2*maxn),pre(maxn),in(maxn),judge(2*maxn);
void dfs(int root,int st,int ed,int p,int level){
if(st>ed) return;
int i=st;
parent[maxn+pre[root]]=p;
depth[maxn+pre[root]]=level;
for(;i<ed;i++) if(in[i]==pre[root]) break;//in[st]==pre[root]
dfs(root+1,st,i-1,maxn+pre[root],level+1);
dfs(root+1+i-st,i+1,ed,maxn+pre[root],level+1);
}
int LCA(int u,int v){
if(parent[u]==-1) return u;
if(parent[v]==-1) return v;
while(depth[u]>depth[v]) u=parent[u];
while(depth[u]<depth[v]) v=parent[v];
while(u!=v){
u=parent[u];
v=parent[v];
}
return u;
}
int main(){
cin>>k>>n;
for(int i=0;i<n;i++) {
cin>>pre[i];
in[i]=pre[i];
judge[maxn+pre[i]]=1;
}
sort(in.begin(),in.begin()+n);
dfs(0,0,n-1,-1,0);
while(k--){
cin>>x>>y;
int root=LCA(maxn+x,maxn+y)-maxn;
if(!judge[maxn+x]&&!judge[maxn+y])
printf("ERROR: %d and %d are not found.\n",x,y);
else if(!judge[maxn+x]||!judge[maxn+y])
printf("ERROR: %d is not found.\n",judge[maxn+x]?y:x);
else if(root==x||root==y)
printf("%d is an ancestor of %d.\n",root,root==x?y:x);
else
printf("LCA of %d and %d is %d.\n",x,y,root);
}
return 0;
}