ホームページ  >  記事  >  Java  >  素集合グラフの学習

素集合グラフの学習

PHPz
PHPzオリジナル
2024-08-15 20:31:48875ブラウズ

Disjoint Set Graph Learning

素集合は、クラスカル最小スパニング ツリーで使用されるデータ構造です。
このデータ構造により、2 つ以上のノードの結合を作成できます。
これにより、2 つのノードがグラフの同じコンポーネントに属しているかどうかを判断できます。
時間計算量は 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");
    }
}

以上が素集合グラフの学習の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。