1143 Lowest Common Ancestor (30 分)

题意

找他的最近公共祖先结点。。听着名字就被糊弄过去了

其实这是道很简单的题,因为他是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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值