static Set<String> res = new HashSet<>(); public static void main(String[] args) { Map<String, Set<String>> subClass = new HashMap<>(); Map<String, Set<String>> instance = new HashMap<>(); Scanner in = new Scanner(System.in); int k = Integer.parseInt(in.nextLine()); for (int i = 0; i < k; i++) { String[] ss = in.nextLine().split(" "); if ("subClassOf".equals(ss[1])) { Set<String> set = subClass.getOrDefault(ss[2], new HashSet<>()); set.add(ss[0]); subClass.put(ss[2], set); } else { Set<String> set = instance.getOrDefault(ss[2], new HashSet<>()); set.add(ss[0]); instance.put(ss[2], set); } } String a = in.nextLine(); dfs(a, subClass, instance); if (res.isEmpty()) { System.out.println("empty"); return; } List<String> r = new ArrayList<>(res); Collections.sort(r); for (int i = 0; i < r.size() -1; i++) { System.out.print(r.get(i)); System.out.print(" "); } System.out.print(r.get(r.size() -1)); } static void dfs(String s, Map<String, Set<String>> subClass, Map<String, Set<String>> instance) { res.addAll(instance.getOrDefault(s, new HashSet<>())); Set<String> set = subClass.get(s); if(set != null && !set.isEmpty()) for (String a : set) { dfs(a, subClass, instance); } }
全部评论
(6) 回帖