java数据结构之并查集

希望大家通过本次的学习后,

能够加深对数组的理解和使用

import java.util.Random;

public class UnionFind {
    
    public static int count = 0 ;
    private int[] parent ;
    private int[] rank ;
    public UnionFind(int size) {
        parent = new int[size] ;
        rank = new int[size] ;
        for(int i = 0 ;i  < parent.length ; i ++) {
            parent[i] = i ;
            rank[i] = 1 ;
        }
    }
    
    public int find(int p) {
        while(p != parent[p]) {
            parent[p] = parent[parent[p]] ;
            p = parent[p] ;            
        }
        return p ;
    }
    
    public int getSize() {
        return parent.length  ;
    }
    
    public boolean isConnected(int p , int q) {
        return find(p) == find(q) ;
    }
    
    public void unionElements(int p , int q) {
        //在查找时进行的路径压缩
        int pRoot = find(p) ;
        int qRoot = find(q) ;
        
        if(rank[pRoot] > rank[qRoot]) {
            parent[qRoot] = pRoot ;

        }else if(rank[pRoot] < rank[qRoot]) {
            parent[pRoot] = qRoot ;
        }else {
            parent[pRoot] = qRoot ;
            rank[qRoot] += 1 ;
        }
    }
    
    private static double testUF(UnionFind uf , int m ) {
        int size = uf.getSize() ;
        Random random = new Random() ;
        
        long startTime  = System.nanoTime() ;
        for(int i = 0 ; i < m ; i ++) {
            int a = random.nextInt(size) ;
            int b = random.nextInt(size) ;
            uf.unionElements(a , b) ;
        }
        for(int i = 0 ; i < m ;i ++) {
            int a = random.nextInt(size) ;
            int b = random.nextInt(size) ;
            if(uf.isConnected(a, b) ) {
                count ++ ;
            }
        }
        System.out.println("连接次数:" + count);
        long endTime = System.nanoTime() ;
        return (endTime - startTime) / 1000000000.0 ;
    }
    public static void main(String[] args) {
        int size = 100000 ;
        int m = 1000000 ;
        
        UnionFind uf = new UnionFind(size) ;
        System.out.println("UnionFind : " + testUF(uf , m) + "s");
     }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值