字母结点型DSU

字母结点型DSU字母节点型DSU:Solution:Useahashmaptostoreamappingbetweenthenodesandtheirparentnodes.Sotoeachitemofthishashmap,thekeyisonenodeandthevalueisitsparentnode.Code:importjava…

字母节点型DSU:
在这里插入图片描述

Solution:

Use a hashmap to store a mapping between the labels of nodes and the labels of their parent nodes. For each item in this hashmap, the key is the label of one node and the value is the label of its parent node.

Code:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DSU { 
   
    private Map<String, String> parent;
    private Map<String, Integer> rank;

    public DSU(String[][] edges) { 
   
        parent = new HashMap<>();
        rank = new HashMap<>();

        for(String[] edge: edges) { 
   
            for(String node: edge) { 
   
                if (!parent.containsKey(node)) { 
   
                    parent.put(node, node);
                    rank.put(node, 0);
                }
            }
        }
    }

    public String find(String s) { 
   
        if(!s.equals(parent.get(s))) { 
   
            String root = find(parent.get(s));
            parent.put(s, root);
        }
        return parent.get(s);
    }

    public void union(String s1, String s2) { 
   
        String s1R = find(s1);
        String s2R = find(s2);

        if(s1R.equals(s2R)) { 
   
            return;
        }else{ 
   
            if(rank.get(s1R) < rank.get(s2R)) { 
   
                parent.put(s1R, s2R);
            }if(rank.get(s1R) > rank.get(s2R)) { 
   
                parent.put(s2R, s1R);
            }else{ 
   
                parent.put(s2R, s1R);
                rank.put(s1R, rank.get(s1R)+1);
            }
        }
    }

    public int getConnectedPart() { 
   
        int connectedPart = 0;
        for(String key: parent.keySet()) { 
   
            if(parent.get(key).equals(key)) { 
   
                connectedPart += 1;
            }
        }
        return connectedPart;
    }

    public static void main(String[] args) { 
   
        String[][] edges = { 
   { 
   "A", "B"}, { 
   "A", "C"}, { 
   "B", "C"}, { 
   "D", "E"}};
        DSU dsu = new DSU(edges);

        for(String[] edge: edges) { 
   
            dsu.union(edge[0], edge[1]);
        }

        int connectedPart = dsu.getConnectedPart();
        System.out.println(connectedPart); // 2
    }

}

今天的文章字母结点型DSU分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/7084.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注