|
| 1 | +/** |
| 2 | + * @param {number} n |
| 3 | + * @param {number[][]} edges |
| 4 | + * @param {number[]} cost |
| 5 | + * @return {number} |
| 6 | + */ |
| 7 | +var minIncrease = function (n, edges, cost) { |
| 8 | + const tree = Array.from({ length: n }, () => []) |
| 9 | + |
| 10 | + for (const e of edges) { |
| 11 | + tree[e[0]].push(e[1]) |
| 12 | + tree[e[1]].push(e[0]) |
| 13 | + } |
| 14 | + |
| 15 | + const changes = [0] |
| 16 | + dfs(0, -1, tree, cost, changes) |
| 17 | + |
| 18 | + return changes[0] |
| 19 | +} |
| 20 | + |
| 21 | +function dfs(node, parent, tree, cost, changes) { |
| 22 | + const childCosts = [] |
| 23 | + |
| 24 | + for (const nei of tree[node]) { |
| 25 | + if (nei === parent) { |
| 26 | + continue |
| 27 | + } |
| 28 | + |
| 29 | + const subCost = dfs(nei, node, tree, cost, changes) |
| 30 | + childCosts.push(subCost) |
| 31 | + } |
| 32 | + |
| 33 | + if (childCosts.length === 0) { |
| 34 | + return cost[node] |
| 35 | + } |
| 36 | + |
| 37 | + const maxCost = Math.max(...childCosts) |
| 38 | + |
| 39 | + for (const c of childCosts) { |
| 40 | + if (c < maxCost) { |
| 41 | + changes[0]++ |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return cost[node] + maxCost |
| 46 | +} |
0 commit comments