登录
首页 >  文章 >  java教程

不相交集图学习

来源:dev.to

时间:2024-08-15 21:24:42 451浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《不相交集图学习》,很明显是关于文章的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

不相交集图学习

不相交集是kruskal最小生成树中使用的一种数据结构。
这种数据结构允许我们创建两个或多个节点的并集。
它让我们确定两个节点是否属于 not 图的同一组成部分。
时间复杂度为 o(4alpha)(如果我们使用路径压缩,否则它将是对数),这是已被证明的恒定时间复杂度。

更多信息请参考

class Main{
    int parent[]  = new int[100000];
    int rank[] = new int[100000];
    void makeSet(){
        for(int i=1;i<=n;i++){
            parent[i] = i; // initially parent of node i is i itself
            rank[i] =0;// intially rank of all the nodes are 0
        }
    }

    int findParent(int node){
        if(node == parent[node]) return node; // ie if the parent of 'node' is 'node' itself then just return the node.
        //return findParent(parent[node]);// else recursively call findParent to get the parent of this union.
        // in order to path conpress (making sure that every node is connected to its parent in the given union)
        return parent[node]  = findParent(parent[node]);
        //example : 7->6->4->3 , here 3 is the parent of this union, so in order to get the parent of 7 which is 3 we can path compress it. like 7->3,6->3,4->3 etc.
    }
    void union(int u, int v){
        u = findParent(u);
        v = findParent(v);
        if(rank[u] < rank[v]) parent[u] =v;
        else if (rank[u] > rank[v]) parent[v] = u;
        else parent[u] =v; // or parent[v] = u;
        // here u and v had the same rank
        //and now v became parent of u hence its rank will increase
        rank[v]++;
    }

    public static void main(String args[]) throws Exception{
        Main m = new Main();
        //if we where given no of nodes as n
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        while(n>0){
            int u = n--;
            int v = n--;
            m.union(u,v);// this will create union of n nodes
        }
        // if 2 and 3 belong to the same component or not find out
        if(findParent(2)! = findParent(3)) System.out.println("Different component");
        else System.out.println("Same component");
    }
}

好了,本文到此结束,带大家了解了《不相交集图学习》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多文章知识!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>