|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +class Solution |
| 6 | +{ |
| 7 | + static ArrayList<Family> famList = new ArrayList<>(); |
| 8 | + static ArrayList<String> candidate = new ArrayList<>(); |
| 9 | + static HashMap<String, Double> result = new HashMap<>(); |
| 10 | + static double maxNum = 0; |
| 11 | + static String answer = ""; |
| 12 | + |
| 13 | + public static void main(String[] args) throws Exception{ |
| 14 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 15 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 16 | + |
| 17 | + int N = Integer.parseInt(st.nextToken()); |
| 18 | + int M = Integer.parseInt(st.nextToken()); |
| 19 | + String king = br.readLine().trim(); |
| 20 | + |
| 21 | + result.put(king, 1.0); |
| 22 | + for (int i = 0; i < N; i++) { |
| 23 | + st = new StringTokenizer(br.readLine()); |
| 24 | + famList.add(new Family(st.nextToken().trim(), st.nextToken().trim(), st.nextToken().trim())); |
| 25 | + } |
| 26 | + for (int i = 0; i < M; i++) { |
| 27 | + candidate.add(br.readLine().trim()); |
| 28 | + } |
| 29 | + |
| 30 | + for (String can : candidate) { |
| 31 | + double res = dfs(can); |
| 32 | + if (maxNum < res) { |
| 33 | + maxNum = res; |
| 34 | + answer = can; |
| 35 | + } |
| 36 | + } |
| 37 | + System.out.println(answer); |
| 38 | + } |
| 39 | + |
| 40 | + public static double dfs(String name) { |
| 41 | + if (!result.containsKey(name)) { |
| 42 | + for (Family fam : famList) { |
| 43 | + if (!fam.c.equals(name)) continue; |
| 44 | + double res = 0.0; |
| 45 | + res += (dfs(fam.p1)/2 + dfs(fam.p2)/2); |
| 46 | + result.put(name, res); |
| 47 | + break; |
| 48 | + } |
| 49 | + } |
| 50 | + if (!result.containsKey(name)) result.put(name, 0.0); |
| 51 | + return result.getOrDefault(name, 0.0); |
| 52 | + } |
| 53 | + |
| 54 | + static class Family { |
| 55 | + String c; |
| 56 | + String p1; |
| 57 | + String p2; |
| 58 | + public Family(String c, String p1, String p2) { |
| 59 | + this.c = c; |
| 60 | + this.p1 = p1; |
| 61 | + this.p2 = p2; |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +``` |
0 commit comments