|
| 1 | +/** |
| 2 | + * @param {number[]} nums |
| 3 | + * @param {number[][]} edges |
| 4 | + * @return {number} |
| 5 | + */ |
| 6 | +const minimumScore = function (nums, edges) { |
| 7 | + const n = nums.length, m = edges.length |
| 8 | + const graph = {} |
| 9 | + const children = {} |
| 10 | + const xor = nums.slice(0) |
| 11 | + const degree = Array(n).fill(0) |
| 12 | + |
| 13 | + for(const [p, q] of edges) { |
| 14 | + if(graph[p] == null) graph[p] = [] |
| 15 | + if(graph[q] == null) graph[q] = [] |
| 16 | + graph[p].push(q) |
| 17 | + graph[q].push(p) |
| 18 | + degree[p]++ |
| 19 | + degree[q]++ |
| 20 | + } |
| 21 | + |
| 22 | + let val = 0 |
| 23 | + const seen = new Set() |
| 24 | + const queue = [] |
| 25 | + for(let i = 0; i < n; i++) { |
| 26 | + val ^= nums[i] |
| 27 | + if(degree[i] === 1) { |
| 28 | + queue.push(i) |
| 29 | + seen.add(i) |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + while(queue.length) { |
| 34 | + const cur = queue.shift() |
| 35 | + for(const nxt of (graph[cur] || [])) { |
| 36 | + if(!seen.has(nxt)) { |
| 37 | + if(children[nxt] == null) children[nxt] = new Set() |
| 38 | + children[nxt].add(cur) |
| 39 | + for(const e of (children[cur] || [])) { |
| 40 | + children[nxt].add(e) |
| 41 | + } |
| 42 | + xor[nxt] ^= xor[cur] |
| 43 | + } |
| 44 | + degree[nxt]-- |
| 45 | + if(degree[nxt] === 1) { |
| 46 | + seen.add(nxt) |
| 47 | + queue.push(nxt) |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + let res = Infinity |
| 53 | + |
| 54 | + for(let i = 0; i < m - 1; i++) { |
| 55 | + for(let j = i + 1; j < m; j++) { |
| 56 | + let [a, b] = edges[i] |
| 57 | + // Let a, c be the lower break points |
| 58 | + if(children[a]?.has(b)) { |
| 59 | + ;[a, b] = [b, a] |
| 60 | + } |
| 61 | + let [c, d] = edges[j] |
| 62 | + if(children[c]?.has(d)) { |
| 63 | + ;[c, d] = [d, c] |
| 64 | + } |
| 65 | + let cur |
| 66 | + if(children[a]?.has(c)) { |
| 67 | + cur = [xor[c], xor[a] ^ xor[c], val ^ xor[a]] |
| 68 | + } else if(children[c]?.has(a)) { |
| 69 | + cur = [xor[a], xor[c] ^ xor[a], val ^ xor[c]] |
| 70 | + } else { |
| 71 | + cur = [xor[a], xor[c], val ^ xor[a] ^ xor[c]] |
| 72 | + } |
| 73 | + res = Math.min(res, Math.max(...cur) - Math.min(...cur)) |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + return res |
| 78 | +} |
| 79 | + |
| 80 | +// another |
| 81 | + |
1 | 82 | /**
|
2 | 83 | * @param {number[]} nums
|
3 | 84 | * @param {number[][]} edges
|
|
0 commit comments