字母节点型DSU:
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 (!ainsKey(node)) {parent.put(node, node);rank.put(node, 0);}}}}public String find(String s) {if(!s.(s))) {String root = (s));parent.put(s, root);}(s);}public void union(String s1, String s2) {String s1R = find(s1);String s2R = find(s2);if(s1R.equals(s2R)) {return;}else{(s1R) < (s2R)) {parent.put(s1R, s2R);}(s1R) > (s2R)) {parent.put(s2R, s1R);}else{parent.put(s2R, s1R);rank.put(s1R, (s1R)+1);}}}public int getConnectedPart() {int connectedPart = 0;for(String key: parent.keySet()) {(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 = ConnectedPart();System.out.println(connectedPart); // 2}}
本文发布于:2024-01-31 09:29:31,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170666457427538.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |