|
| 1 | +package g3401_3500.s3486_longest_special_path_ii; |
| 2 | + |
| 3 | +// #Hard #Array #Hash_Table #Tree #Prefix_Sum #Depth_First_Search |
| 4 | +// #2025_03_17_Time_166_ms_(100.00%)_Space_105.50_MB_(100.00%) |
| 5 | + |
| 6 | +import java.util.ArrayList; |
| 7 | +import java.util.Arrays; |
| 8 | +import java.util.Comparator; |
| 9 | +import java.util.HashMap; |
| 10 | +import java.util.List; |
| 11 | +import java.util.Map; |
| 12 | + |
| 13 | +@SuppressWarnings("java:S107") |
| 14 | +public class Solution { |
| 15 | + public int[] longestSpecialPath(int[][] edges, int[] nums) { |
| 16 | + int[] ans = {0, 1}; |
| 17 | + Map<Integer, List<int[]>> graph = new HashMap<>(); |
| 18 | + for (int[] edge : edges) { |
| 19 | + int a = edge[0]; |
| 20 | + int b = edge[1]; |
| 21 | + int c = edge[2]; |
| 22 | + graph.computeIfAbsent(a, k -> new ArrayList<>()).add(new int[] {b, c}); |
| 23 | + graph.computeIfAbsent(b, k -> new ArrayList<>()).add(new int[] {a, c}); |
| 24 | + } |
| 25 | + List<Integer> costs = new ArrayList<>(); |
| 26 | + Map<Integer, Integer> last = new HashMap<>(); |
| 27 | + dfs(0, 0, -1, new ArrayList<>(Arrays.asList(0, 0)), nums, graph, costs, last, ans); |
| 28 | + return ans; |
| 29 | + } |
| 30 | + |
| 31 | + private void dfs( |
| 32 | + int node, |
| 33 | + int currCost, |
| 34 | + int prev, |
| 35 | + List<Integer> left, |
| 36 | + int[] nums, |
| 37 | + Map<Integer, List<int[]>> graph, |
| 38 | + List<Integer> costs, |
| 39 | + Map<Integer, Integer> last, |
| 40 | + int[] ans) { |
| 41 | + int nodeColorIndexPrev = last.getOrDefault(nums[node], -1); |
| 42 | + last.put(nums[node], costs.size()); |
| 43 | + costs.add(currCost); |
| 44 | + int diff = currCost - costs.get(left.get(0)); |
| 45 | + int length = costs.size() - left.get(0); |
| 46 | + if (diff > ans[0] || (diff == ans[0] && length < ans[1])) { |
| 47 | + ans[0] = diff; |
| 48 | + ans[1] = length; |
| 49 | + } |
| 50 | + for (int[] next : graph.getOrDefault(node, new ArrayList<>())) { |
| 51 | + int nextNode = next[0]; |
| 52 | + int nextCost = next[1]; |
| 53 | + if (nextNode == prev) { |
| 54 | + continue; |
| 55 | + } |
| 56 | + List<Integer> nextLeft = new ArrayList<>(left); |
| 57 | + if (last.containsKey(nums[nextNode])) { |
| 58 | + nextLeft.add(last.get(nums[nextNode]) + 1); |
| 59 | + } |
| 60 | + nextLeft.sort(Comparator.naturalOrder()); |
| 61 | + while (nextLeft.size() > 2) { |
| 62 | + nextLeft.remove(0); |
| 63 | + } |
| 64 | + dfs(nextNode, currCost + nextCost, node, nextLeft, nums, graph, costs, last, ans); |
| 65 | + } |
| 66 | + last.put(nums[node], nodeColorIndexPrev); |
| 67 | + costs.remove(costs.size() - 1); |
| 68 | + } |
| 69 | +} |
0 commit comments