zoukankan      html  css  js  c++  java
  • Build Relationship Tree

    import java.util.*;
    
    class Node{
        String val;
       Set<Node> children = new  HashSet<Node>(); // at most 15 children;
        public Node(String val){
            this.val = val;
            this.children = new HashSet<>();
        }
    }
    
    public class RelationTree {
        private void travel(Node root){
            System.out.println(root.val);
            for(Node n: root.children){
                travel(n);
            }
        }
        
        private Node findRelations(String[] input) {
            // TODO Auto-generated method stub
            HashMap<String, Node> map = new HashMap<String, Node>();
            Set<String> childrenSet = new HashSet<String>();
            for(int i = 0 ; i < input.length - 2 ; i++){
                String manager = input[i].split("->")[0];
                String person = input[i].split("->")[1];
                Node managerNode = new Node(manager);
                Node personNode = new Node(person);
                childrenSet.add(person);
                if(map.containsKey(manager)){
                    if(map.containsKey(person)){
                        map.get(manager).children.add(map.get(person));
                    }
                    else{
                        map.get(manager).children.add(personNode);
                        map.put(person, personNode);
                    }
                }
                else{
                    map.put(manager, managerNode);
                    if(map.containsKey(person)){
                        managerNode.children.add(map.get(person));
                    }
                    else{
                        managerNode.children.add(personNode);
                        map.put(person, personNode);
                    }
                }
            }
            //find root
            Node root = null;
            for(int i = 0 ; i < input.length - 2 ; i++){
                String manager = input[i].split("->")[0];
                if(!childrenSet.contains(manager)){
                    root = map.get(manager);
                    break;
                }
            }
            
            return root;
        }
    
    }
  • 相关阅读:
    bzoj3757 苹果树
    bzoj2743 [HEOI2012]采花
    bzoj4241 历史研究
    bzoj4448 [Scoi2015]情报传递
    bzoj3295 [Cqoi2011]动态逆序对
    bzoj4034 [HAOI2015]T2
    bzoj3339 Rmq Problem
    BZOJ 1017 魔兽地图
    BZOJ 1021 循环的债务
    SUOI #37 清点更多船只
  • 原文地址:https://www.cnblogs.com/joannacode/p/5998950.html
Copyright © 2011-2022 走看看