Skip to content

Commit 6adb4b1

Browse files
authored
Update 2322-minimum-score-after-removals-on-a-tree.js
1 parent 008496e commit 6adb4b1

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

2322-minimum-score-after-removals-on-a-tree.js

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,3 +139,96 @@ var minimumScore = function (nums, edges) {
139139
return (child_xor[i] = ans)
140140
}
141141
}
142+
143+
// another
144+
145+
/**
146+
* @param {number[]} nums
147+
* @param {number[][]} edges
148+
* @return {number}
149+
*/
150+
const minimumScore = function (nums, edges) {
151+
const n = nums.length,
152+
m = edges.length
153+
const graph = {},
154+
degree = Array(n).fill(0)
155+
const children = [],
156+
vArr = nums.slice()
157+
for (let i = 0; i < n; i++) children[i] = new Set()
158+
for (const [u, v] of edges) {
159+
if (graph[u] == null) graph[u] = []
160+
if (graph[v] == null) graph[v] = []
161+
graph[u].push(v)
162+
graph[v].push(u)
163+
degree[u]++
164+
degree[v]++
165+
}
166+
let v = 0,
167+
q = []
168+
const seen = new Set()
169+
for (let i = 0; i < n; i++) {
170+
v ^= nums[i]
171+
if (degree[i] === 1) {
172+
q.push(i)
173+
seen.add(i)
174+
}
175+
}
176+
177+
while (q.length) {
178+
const tmp = []
179+
const size = q.length
180+
for (let i = 0; i < size; i++) {
181+
const cur = q[i]
182+
for (const nxt of graph[cur]) {
183+
// chidlren
184+
// vArr
185+
if (!seen.has(nxt)) {
186+
children[nxt].add(cur)
187+
children[nxt] = mergeSet(children[nxt], children[cur])
188+
vArr[nxt] ^= vArr[cur]
189+
}
190+
degree[nxt]--
191+
if (degree[nxt] === 1) {
192+
tmp.push(nxt)
193+
seen.add(nxt)
194+
}
195+
}
196+
}
197+
198+
q = tmp
199+
}
200+
201+
let res = Infinity
202+
for (let i = 0; i < m - 1; i++) {
203+
for (let j = i + 1; j < m; j++) {
204+
let [a, b] = edges[i]
205+
if (children[a].has(b)) {
206+
;[a, b] = [b, a]
207+
}
208+
let [c, d] = edges[j]
209+
if (children[c].has(d)) {
210+
;[c, d] = [d, c]
211+
}
212+
if (children[c].has(a)) {
213+
const tmp = [vArr[a], vArr[c] ^ vArr[a], v ^ vArr[c]]
214+
res = Math.min(res, Math.max(...tmp) - Math.min(...tmp))
215+
} else if (children[a].has(c)) {
216+
const tmp = [vArr[c], vArr[a] ^ vArr[c], v ^ vArr[a]]
217+
res = Math.min(res, Math.max(...tmp) - Math.min(...tmp))
218+
} else {
219+
const tmp = [vArr[a], vArr[c], v ^ vArr[a] ^ vArr[c]]
220+
res = Math.min(res, Math.max(...tmp) - Math.min(...tmp))
221+
}
222+
}
223+
}
224+
225+
return res
226+
}
227+
228+
function mergeSet(s, t) {
229+
for (const e of t) {
230+
s.add(e)
231+
}
232+
return s
233+
}
234+

0 commit comments

Comments
 (0)