首页 > 其他 > 详细

并查集

时间:2020-03-11 00:15:34      阅读:68      评论:0      收藏:0      [点我收藏+]
public class unionFindSet {
    public static void main(String[] args) {
        int n = 100;
        node[] nodes = new node[100];
        for (int i = 0; i < n; i++) {
            nodes[i] = new node();
            nodes[i].data = i;
            nodes[i].parent = nodes[i];
        }
        union(nodes[1], nodes[2]);
        for (int i = 0; i < nodes.length; i++) {
            System.out.println(find(nodes[i]).count);
        }
    }
    static node findzip(node n) {
        n.parent = find(n);
        return n.parent;
    }
    static node find(node n) {
        if (n.parent == n)
            return n;
        return find(n.parent);
    }

    static void union(node n, node m) {
        node nparent = findzip(n);
        node mparent = findzip(m);
        nparent.count = nparent.count + mparent.count;
        mparent.parent = nparent;
    }

    static class node {
        int data;
        int count = 1;
        node parent;
        }
    }
}

并查集

原文:https://www.cnblogs.com/continued258/p/12459393.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!