|
| 1 | +/** |
| 2 | + * @param {number[]} nums |
| 3 | + * @param {number[][]} edges |
| 4 | + * @return {number} |
| 5 | + */ |
| 6 | +var minimumScore = function(nums, edges) { |
| 7 | + const n = nums.length; |
| 8 | + |
| 9 | + const graph = Array.from({ length: n }, () => []); |
| 10 | + |
| 11 | + for (let i = 0; i < edges.length; i++) { |
| 12 | + const [a, b] = edges[i]; |
| 13 | + graph[a].push(b); |
| 14 | + graph[b].push(a); |
| 15 | + } |
| 16 | + |
| 17 | + const xor = new Array(n).fill(0); |
| 18 | + const inTime = new Array(n).fill(0); |
| 19 | + const outTime = new Array(n).fill(0); |
| 20 | + |
| 21 | + let time = 0; |
| 22 | + |
| 23 | + function dfs(node, parent) { |
| 24 | + inTime[node] = time++; |
| 25 | + xor[node] = nums[node]; |
| 26 | + |
| 27 | + for (let i = 0; i < graph[node].length; i++) { |
| 28 | + const next = graph[node][i]; |
| 29 | + |
| 30 | + if (next === parent) continue; |
| 31 | + |
| 32 | + dfs(next, node); |
| 33 | + |
| 34 | + xor[node] ^= xor[next]; |
| 35 | + } |
| 36 | + |
| 37 | + outTime[node] = time; |
| 38 | + } |
| 39 | + |
| 40 | + dfs(0, -1); |
| 41 | + |
| 42 | + // a가 b의 조상인지 확인 |
| 43 | + function isParent(a, b) { |
| 44 | + return inTime[a] <= inTime[b] && |
| 45 | + outTime[b] <= outTime[a]; |
| 46 | + } |
| 47 | + |
| 48 | + const total = xor[0]; |
| 49 | + let ans = Infinity; |
| 50 | + |
| 51 | + // root를 제외한 각 노드는 |
| 52 | + // 부모와 연결된 간선을 하나씩 가지고 있음 |
| 53 | + for (let i = 1; i < n; i++) { |
| 54 | + for (let j = i + 1; j < n; j++) { |
| 55 | + |
| 56 | + let a; |
| 57 | + let b; |
| 58 | + let c; |
| 59 | + |
| 60 | + if (isParent(i, j)) { |
| 61 | + // j가 i 서브트리 안에 있음 |
| 62 | + a = xor[j]; |
| 63 | + b = xor[i] ^ xor[j]; |
| 64 | + c = total ^ xor[i]; |
| 65 | + |
| 66 | + } else if (isParent(j, i)) { |
| 67 | + // i가 j 서브트리 안에 있음 |
| 68 | + a = xor[i]; |
| 69 | + b = xor[j] ^ xor[i]; |
| 70 | + c = total ^ xor[j]; |
| 71 | + |
| 72 | + } else { |
| 73 | + // 서로 다른 서브트리 |
| 74 | + a = xor[i]; |
| 75 | + b = xor[j]; |
| 76 | + c = total ^ xor[i] ^ xor[j]; |
| 77 | + } |
| 78 | + |
| 79 | + const max = Math.max(a, b, c); |
| 80 | + const min = Math.min(a, b, c); |
| 81 | + |
| 82 | + ans = Math.min(ans, max - min); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + return ans; |
| 87 | +}; |
0 commit comments