栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java并查集

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java并查集

并查集通用模板 今天第一次遇到并查集题目,直接蒙了,这是用来解决图的连通性问题的数据结构 有4个力扣题目链接

130 被围绕的区域
2316 统计无向图中无法到达的点数
990 等式方程
128 最长连续序列

 public  class Node{
        Integer value;
        public Node(Integer v){
            value = v;
        }
    }
    public  class UnionSet{
        //V -> 节点 一一对应关系,值 - 》 值对应的节点
        public HashMap> nodes = new HashMap<>();
        //一个节点的父亲节点是谁作为一组记录,存在parent表里
        public HashMap,Node> parents = new HashMap<>();
        //只有一个点,它是某个集合代表点的情况才有记录,这个点类似头节点
        public HashMap,Integer> sizeMap = new HashMap<>();
        public UnionSet(Integer value){
            for(Integer i=0;i< value;i++){
                Node node = new Node<>(i);
                nodes.put(i,node);
                parents.put(node,node);
                sizeMap.put(node,1);
            }
        }
        //从点current一直往上找,找到不能再往上的代表点
        public Node findFather(Node cur){
            Stack> path = new Stack<>();
            while(cur != parents.get(cur)){
                path.push(cur);
                cur = parents.get(cur);
            }
            //cur头节点
            while(!path.isEmpty()){
                parents.put(path.pop(),cur);
            }
            return cur;
        }
        public boolean isSameSet(Integer a,Integer b){
            if(!nodes.containsKey(a) || nodes.containsKey(b)){
                return false;
            }
            return findFather(nodes.get(a)) == findFather(nodes.get(b));
        }
        public void union(Integer a,Integer b){
            if(!nodes.containsKey(a) || !nodes.containsKey(b)) return;
            Node aHead = findFather(nodes.get(a));
            Node bHead = findFather(nodes.get(b));
            if(aHead != bHead){
                int aSetSize = sizeMap.get(aHead);
                int bSetSize = sizeMap.get(bHead);
                if(aSetSize >= bSetSize){
                    parents.put(bHead,aHead);
                    sizeMap.put(aHead,aSetSize + bSetSize);
                    sizeMap.remove(bHead);
                }else {
                    parents.put(aHead,bHead);
                    sizeMap.put(bHead,aSetSize + bSetSize);
                    sizeMap.remove(aHead);
                }
            }
        }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/995439.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号