|
| 1 | +/** |
| 2 | + * 3067. Count Pairs of Connectable Servers in a Weighted Tree Network |
| 3 | + * https://leetcode.com/problems/count-pairs-of-connectable-servers-in-a-weighted-tree-network/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an unrooted weighted tree with n vertices representing servers numbered from 0 |
| 7 | + * to n - 1, an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional edge |
| 8 | + * between vertices ai and bi of weight weighti. You are also given an integer signalSpeed. |
| 9 | + * |
| 10 | + * Two servers a and b are connectable through a server c if: |
| 11 | + * - a < b, a != c and b != c. |
| 12 | + * - The distance from c to a is divisible by signalSpeed. |
| 13 | + * - The distance from c to b is divisible by signalSpeed. |
| 14 | + * - The path from c to b and the path from c to a do not share any edges. |
| 15 | + * |
| 16 | + * Return an integer array count of length n where count[i] is the number of server pairs that are |
| 17 | + * connectable through the server i. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number[][]} edges |
| 22 | + * @param {number} signalSpeed |
| 23 | + * @return {number[]} |
| 24 | + */ |
| 25 | +var countPairsOfConnectableServers = function(edges, signalSpeed) { |
| 26 | + const n = edges.length + 1; |
| 27 | + const graph = Array.from({ length: n }, () => []); |
| 28 | + for (const [u, v, w] of edges) { |
| 29 | + graph[u].push([v, w]); |
| 30 | + graph[v].push([u, w]); |
| 31 | + } |
| 32 | + |
| 33 | + const result = new Array(n).fill(0); |
| 34 | + for (let i = 0; i < n; i++) { |
| 35 | + result[i] = countValidPairs(i); |
| 36 | + } |
| 37 | + return result; |
| 38 | + |
| 39 | + function countValidPairs(root) { |
| 40 | + function dfs(node, parent, distance) { |
| 41 | + let count = distance % signalSpeed === 0 ? 1 : 0; |
| 42 | + for (const [next, weight] of graph[node]) { |
| 43 | + if (next !== parent) { |
| 44 | + count += dfs(next, node, distance + weight); |
| 45 | + } |
| 46 | + } |
| 47 | + return count; |
| 48 | + } |
| 49 | + |
| 50 | + let totalPairs = 0; |
| 51 | + const counts = []; |
| 52 | + for (const [child, weight] of graph[root]) { |
| 53 | + const count = dfs(child, root, weight); |
| 54 | + counts.push(count); |
| 55 | + } |
| 56 | + |
| 57 | + let sum = 0; |
| 58 | + for (const count of counts) { |
| 59 | + totalPairs += sum * count; |
| 60 | + sum += count; |
| 61 | + } |
| 62 | + return totalPairs; |
| 63 | + } |
| 64 | +}; |
0 commit comments