Count Pairs of Connectable Servers in a Weighted Tree Network Problem
Description
LeetCode Problem 3067.
You are given an unrooted weighted tree with n vertices representing servers numbered from 0 to n - 1, an array edges where edges[i] = [a_i, b_i, weight_i] represents a bidirectional edge between vertices a_i and b_i of weight weight_i. You are also given an integer signalSpeed.
Two servers a and b are connectable through a server c if:
a < b,a != candb != c.- The distance from
ctoais divisible bysignalSpeed. - The distance from
ctobis divisible bysignalSpeed. - The path from
ctoband the path fromctoado not share any edges.
Return an integer array count of length n where count[i] is the number of server pairs that are connectable through the server i.
Example 1:

Input: edges = [[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]], signalSpeed = 1
Output: [0,4,6,6,4,0]
Explanation: Since signalSpeed is 1, count[c] is equal to the number of pairs of paths that start at c and do not share any edges.
In the case of the given path graph, count[c] is equal to the number of servers to the left of c multiplied by the servers to the right of c.
Example 2:

Input: edges = [[0,6,3],[6,5,3],[0,3,1],[3,2,7],[3,1,6],[3,4,2]], signalSpeed = 3
Output: [2,0,0,0,0,0,2]
Explanation: Through server 0, there are 2 pairs of connectable servers: (4, 5) and (4, 6).
Through server 6, there are 2 pairs of connectable servers: (4, 5) and (0, 5).
It can be shown that no two servers are connectable through servers other than 0 and 6.
Constraints:
2 <= n <= 1000edges.length == n - 1edges[i].length == 30 <= a_i, b_i < nedges[i] = [a_i, b_i, weight_i]1 <= weight_i <= 10^61 <= signalSpeed <= 10^6- The input is generated such that
edgesrepresents a valid tree.
Solution
Approach: Enumeration + DFS
Build an adjacency list g. Try every node a as the middle server. For each neighbor b of a, run a DFS away from a that counts the nodes whose distance to a is divisible by signalSpeed; call the count t. Pairs in different branches never share an edge, so this branch adds s * t pairs, where s is the sum of the counts of the earlier branches. Then add t to s.
Complexity: O(n^2) time and O(n) extra space, where n is the number of servers.
class Solution:
def countPairsOfConnectableServers(
self, edges: List[List[int]], signalSpeed: int
) -> List[int]:
def dfs(a: int, fa: int, ws: int) -> int:
cnt = 0 if ws % signalSpeed else 1
for b, w in g[a]:
if b != fa:
cnt += dfs(b, a, ws + w)
return cnt
n = len(edges) + 1
g = [[] for _ in range(n)]
for a, b, w in edges:
g[a].append((b, w))
g[b].append((a, w))
ans = [0] * n
for a in range(n):
s = 0
for b, w in g[a]:
t = dfs(b, a, w)
ans[a] += s * t
s += t
return ans