1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| static class TreeNode { int id; int val; List<TreeNode> children; public TreeNode(int id, int val) { this.id = id; this.val = val; children = new ArrayList<>(); } }
static List<Integer> primeQuery(int n, List<Integer> first, List<Integer> second, List<Integer> values, List<Integer> queries) { if (first == null || second == null || first.size() != second.size() || values.size() != n) { return null; } Map<Integer, Set<Integer>> edgeMap = new HashMap<>(); for (int i = 0; i < first.size(); i++) { edgeMap.putIfAbsent(first.get(i), new HashSet<>()); edgeMap.putIfAbsent(second.get(i), new HashSet<>()); edgeMap.get(first.get(i)).add(second.get(i)); edgeMap.get(second.get(i)).add(first.get(i)); } Map<Integer, TreeNode> id2Node = new HashMap<>(); TreeNode root = constructTree(edgeMap, values, id2Node); List<Integer> ans = new ArrayList<>(); Map<Integer, Integer> countCache = new HashMap<>(); Map<Integer, Boolean> primeCache = new HashMap<>(); for (int query : queries) { ans.add(getPrimeCount(id2Node.get(query), countCache, primeCache)); } return ans; }
static TreeNode constructTree(Map<Integer, Set<Integer>> edgeMap, List<Integer> values, Map<Integer, TreeNode> id2Node) { Queue<TreeNode> q = new LinkedList<>(); TreeNode root = new TreeNode(1, values.get(0)); id2Node.put(1, root); q.add(root); while (!q.isEmpty()) { TreeNode curr = q.poll(); Set<Integer> childIds = edgeMap.get(curr.id); if (childIds == null) { continue; } for (int childId : childIds) { TreeNode child = new TreeNode(childId, values.get(childId - 1)); id2Node.put(childId, child); q.offer(child); curr.children.add(child); edgeMap.get(childId).remove(curr.id); } edgeMap.remove(curr.id); } return root; }
static int getPrimeCount(TreeNode node, Map<Integer, Integer> countCache, Map<Integer, Boolean> primeCache) { if (node == null) { return 0; } if (countCache.containsKey(node.id)) { return countCache.get(node.id); } int count = isPrime(node.val, primeCache) ? 1 : 0; for (TreeNode child : node.children) { count += getPrimeCount(child, countCache, primeCache); } countCache.put(node.id, count); return count; }
static boolean isPrime(int val, Map<Integer, Boolean> primeCache) { if (primeCache.containsKey(val)) { return primeCache.get(val); } if (val <= 1) { primeCache.put(val, false); return false; } int limit = (int) Math.sqrt(val); for (int i = 2; i <= limit; i++) { if (val % i == 0) { primeCache.put(val, false); return false; } } primeCache.put(val, true); return true; }
|