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
|
class Solution {
public int[] longestSpecialPath(int[][] edges, int[] nums) {
int n = nums.length;
List<int[]>[] g = new List[n];
for (int i = 0; i < n; i++) g[i] = new ArrayList<>();
for (int[] e : edges) {
g[e[0]].add(new int[]{e[1], e[2]});
g[e[1]].add(new int[]{e[0], e[2]});
}
int[] ans = new int[]{0, n+1};
dfs(0, -1, new HashMap<>(), 0, 0, 1, g, nums, ans);
for (int i = 1; i < n; i++) {
dfs(i, -1, new HashMap<>(), 0, 0, 1, g, nums, ans);
}
return ans;
}
void dfs(int u, int p, Map<Integer,Integer> cnt, int twice, int len, int nodes, List<int[]>[] g, int[] nums, int[] ans) {
cnt.put(nums[u], cnt.getOrDefault(nums[u], 0) + 1);
if (len > ans[0] || (len == ans[0] && nodes < ans[1])) {
ans[0] = len;
ans[1] = nodes;
}
for (int[] vw : g[u]) {
int v = vw[0], w = vw[1];
if (v == p) continue;
cnt.put(nums[v], cnt.getOrDefault(nums[v], 0) + 1);
if (cnt.get(nums[v]) == 2) twice++;
if (cnt.get(nums[v]) <= 2 && twice <= 1) {
dfs(v, u, cnt, twice, len + w, nodes + 1, g, nums, ans);
}
if (cnt.get(nums[v]) == 2) twice--;
cnt.put(nums[v], cnt.get(nums[v]) - 1);
}
cnt.put(nums[u], cnt.get(nums[u]) - 1);
}
}
|