|
| 1 | +/** |
| 2 | + * @param {number[][]} edges |
| 3 | + * @return {number[]} |
| 4 | + */ |
| 5 | +var timeTaken = function(edges) { |
| 6 | + let n = edges.length + 1; |
| 7 | + let adj = Array.from({ length: n }, () => []); |
| 8 | + for (let edge of edges) { |
| 9 | + adj[edge[0]].push(edge[1]); |
| 10 | + adj[edge[1]].push(edge[0]); |
| 11 | + } |
| 12 | + |
| 13 | + // first, use 0 as root and calculate below: |
| 14 | + // far1[i]: the farthest children for the subtree with root i |
| 15 | + // far2[i]: the second farthest children for the subtree with root i |
| 16 | + let far1 = Array(n).fill(0); |
| 17 | + let far2 = Array(n).fill(0); |
| 18 | + buildFar(0, adj, far1, far2); |
| 19 | + |
| 20 | + // by far1 and far2, we can use re-rooting to help us find the answer |
| 21 | + let ans = Array(n).fill(0); |
| 22 | + calcOthers(0, 0, adj, far1, far2, ans); |
| 23 | + |
| 24 | + return ans; |
| 25 | +}; |
| 26 | + |
| 27 | +function buildFar(curr, adj, far1, far2) { |
| 28 | + let maxChild1 = 0, maxChild2 = 0; |
| 29 | + // Iterate through each child (branch), and find the two farthest children. |
| 30 | + for (let child of adj[curr]) { |
| 31 | + if (child <= curr) continue; |
| 32 | + |
| 33 | + buildFar(child, adj, far1, far2); |
| 34 | + let dist = ((child & 1) ? 1 : 2) + far1[child]; |
| 35 | + if (dist >= maxChild1) { |
| 36 | + maxChild2 = maxChild1; |
| 37 | + maxChild1 = dist; |
| 38 | + } else if (dist > maxChild2) { |
| 39 | + maxChild2 = dist; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + far1[curr] = maxChild1; |
| 44 | + far2[curr] = maxChild2; |
| 45 | +} |
| 46 | + |
| 47 | +function calcOthers(curr, parentDist, adj, far1, far2, ans) { |
| 48 | + // parentDist: the farthest distance when node[parent] is the root |
| 49 | + |
| 50 | + ans[curr] = Math.max(parentDist, far1[curr]); |
| 51 | + |
| 52 | + for (let child of adj[curr]) { |
| 53 | + if (child < curr) continue; |
| 54 | + |
| 55 | + let toParent = (curr & 1) ? 1 : 2; |
| 56 | + let toChild = (child & 1) ? 1 : 2; |
| 57 | + // For this child, exclude itself or it is not correct |
| 58 | + // (If the branch containing this child is the farthest for node curr, we should use the second farthest) |
| 59 | + let farthestChildExceptThisChild = (far1[curr] === (toChild + far1[child])) ? far2[curr] : far1[curr]; |
| 60 | + |
| 61 | + calcOthers(child, toParent + Math.max(parentDist, farthestChildExceptThisChild), adj, far1, far2, ans); |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | + |
| 66 | + |
0 commit comments