> Java > java지도 시간 > 본문

서로소 집합 그래프 학습

PHPz
풀어 주다: 2024-08-15 20:31:48
원래의
881명이 탐색했습니다.

Disjoint Set Graph Learning

Disjoint Set은 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");
    }
}
로그인 후 복사

위 내용은 서로소 집합 그래프 학습의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!