zoukankan      html  css  js  c++  java
  • 19.tarjan最近公共祖先

        int find(int i){
            return f[i]==i?i:f[i]=find(f[i]);
        }
        int Union(int nd1,int nd2){
            int a=find(nd1);
            int b=find(nd2);
            if(a==b) return 0;
            if(rank[a]<=rank[b]){
                f[a]=b;
                rank[b]+=rank[a];
            }
            else {
                f[b]=a;
                rank[a]+=rank[b];
            }
            return 1;
        }
        void LCA(int root){
            int i,sz;
            an[root]=root;//首先自成一个集合
            //sz=node[root].size();
            //for(i=0;i<sz;i++){
            if(lc[root]!=-1){
                LCA(lc[root]);//递归子树
                Union(root,lc[root]);//将子树和root并到一块 
                an[find(lc[root])]=root;
            }//修改子树的祖先也指向root
            if(rc[root]!=-1){
                LCA(rc[root]);//递归子树
                Union(root,rc[root]);//将子树和root并到一块 
                an[find(rc[root])]=root;//修改子树的祖先也指向root
            }
            vis[root]=1;
            sz=que[root].size();
            for(i=0;i<sz;i++){
                if(vis[que[root][i]]){
                    printf("%d
    ",ff=an[find(que[root][i])]);///root和que[root][i]所表示的值的最近公共祖先
                    return ;
                }
            }
            return ;
        }
        int dfs(TreeNode* root){
            if(!root) return -1;;
            lc[root->val]=dfs(root->left);
            rc[root->val]=dfs(root->right);
            rank[root->val]=1;
            f[root->val]=root->val;
            return root->val;
        }

    ps:最好用标号,不用root->val值

    que[5].push_back(6)代表查询5-6的最近公共祖先

  • 相关阅读:
    chess「dp」
    e[树上主席树]
    d[贪心]
    神盐皇
    LA 8043. ACM-ICPC World Finals 2017 E. Need for Speed
    八数码问题
    UVa 679. Dropping Balls
    关于时间复杂度
    欧拉序列 (Euler Tour)
    莫队算法
  • 原文地址:https://www.cnblogs.com/apo2019/p/13384347.html
Copyright © 2011-2022 走看看