zoukankan      html  css  js  c++  java
  • 1151 LCA in a Binary Tree (30 分)

    额,这不是和1143 Lowest Common Ancestor (30 分)一模一样吗。

    const int N=10010;
    int fa[N];
    unordered_map<int,int> pos;
    int pre[N],in[N];
    bool vis[N];
    int n,m;
    
    int build(int prel,int prer,int inl,int inr)
    {
        if(prel > prer) return -1;
    
        int root=pre[prel];
        int k=pos[root];
        int leftLen=k-inl;
        int lchild=build(prel+1,prel+leftLen,inl,k-1);
        int rchild=build(prel+leftLen+1,prer,k+1,inr);
    
        if(~lchild) fa[lchild]=k;
        if(~rchild) fa[rchild]=k;
        return k;
    }
    
    int LCA(int u,int v)
    {
        memset(vis,0,sizeof vis);
        vis[u]=true;
        while(fa[u])
        {
            u=fa[u];
            vis[u]=true;
        }
    
        while(!vis[v]) v=fa[v];
        return v;
    }
    
    int main()
    {
        cin>>m>>n;
    
        for(int i=1;i<=n;i++)
        {
            cin>>in[i];
            pos[in[i]]=i;
        }
        for(int i=1;i<=n;i++) cin>>pre[i];
    
        build(1,n,1,n);
    
        while(m--)
        {
            int u,v;
            cin>>u>>v;
            if(pos.count(u) == 0 && pos.count(v) == 0)
                printf("ERROR: %d and %d are not found.",u,v);
            else if(pos.count(u) == 0)
                printf("ERROR: %d is not found.",u);
            else if(pos.count(v) == 0)
                printf("ERROR: %d is not found.",v);
            else
            {
                u=pos[u],v=pos[v];
                int lca=LCA(u,v);
                if(lca != u && lca != v)
                    printf("LCA of %d and %d is %d.",in[u],in[v],in[lca]);
                else if(lca == u)
                    printf("%d is an ancestor of %d.",in[u],in[v]);
                else
                    printf("%d is an ancestor of %d.",in[v],in[u]);
            }
            puts("");
        }
        //system("pause");
        return 0;
    }
    
  • 相关阅读:
    iOS中的HTTPS
    HTTPS抓包之Charles
    组件化开发的一些思考
    Xcode 调试技巧
    iOS崩溃日志分析
    iOS依赖库管理工具之Carthage
    13.类的关系总结
    12.组合(Composition)
    11.聚合(Aggregation)
    10.关联(Association)
  • 原文地址:https://www.cnblogs.com/fxh0707/p/14523093.html
Copyright © 2011-2022 走看看