并查集(压缩路径)

package com.u5bf.java;

import java.util.Arrays;

public class DisjointSets {
    private int[] set;
    private int size;

    public DisjointSets(int length) {
        this.set = new int[length];
        Arrays.fill(this.set, -1);
        this.size = length;
    }

    public int find(int x) {
        int root = x;
        while (set[root] >= 0) {
            root = set[root];
        }
        // 压缩路径
        while (x != root) {
            int t = set[x];
            set[x] = root;
            x = t;
        }
        return x;
    }

    public boolean union(int x, int y) {
        int xRoot = find(x);
        int yRoot = find(y);
        if (xRoot == yRoot) {
        	return false; // 属于同一个集合直接退出      
        }
        if (set[xRoot] <= set[yRoot]) { // xRoot 节点数更多
            set[xRoot] += set[yRoot]; // 累加节点总数
            set[yRoot] = xRoot;
        } else {
            set[yRoot] += set[xRoot];
            set[xRoot] = yRoot;
        }
        this.size--;
        return true;
    }

    public int getSize() {
        return this.size;
    }

    public static void main(String[] args) {
        DisjointSets set = new DisjointSets(10);
        set.union(1, 2);
        set.union(3, 4);
        set.union(5, 6);
        set.union(7, 8);
        set.union(8, 9);
        set.union(1, 8);
        set.union(0, 5);
        set.union(1, 9);

        System.out.println("并查集的个数为:" + set.getSize());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值