Count Pairs of Connectable Servers in a Weighted Tree Network - Problem
You are given an unrooted weighted tree with n vertices representing servers numbered from 0 to n - 1, an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional edge between vertices ai and bi of weight weighti.
You are also given an integer signalSpeed.
Two servers a and b are connectable through a server c if:
a < ba != candb != c- The distance from
ctoais divisible bysignalSpeed - The distance from
ctobis divisible bysignalSpeed - The path from
ctoaand the path fromctobdo 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.
Input & Output
Example 1 — Basic Tree Network
$
Input:
edges = [[0,1,1],[1,2,5],[2,3,13],[1,4,9],[4,5,2]], signalSpeed = 1
›
Output:
[0,4,0,0,0,0]
💡 Note:
With signalSpeed=1, all distances are valid. Server 1 can connect 4 pairs through its central position in the tree structure.
Example 2 — Specific Signal Speed
$
Input:
edges = [[0,6,3],[6,4,2],[6,3,3],[4,5,2],[4,1,4],[4,2,1]], signalSpeed = 3
›
Output:
[0,0,0,0,0,0,2]
💡 Note:
Only server 6 can act as a hub. Distances must be divisible by 3, creating 2 valid pairs through server 6.
Example 3 — Linear Chain
$
Input:
edges = [[0,1,2],[1,2,4]], signalSpeed = 2
›
Output:
[0,1,0]
💡 Note:
In a 3-node linear chain, only the middle server (1) can connect the endpoints since both distances are divisible by 2.
Constraints
- 1 ≤ n ≤ 1000
- edges.length == n - 1
- 1 ≤ ai, bi ≤ n - 1
- ai != bi
- 1 ≤ weighti ≤ 106
- 1 ≤ signalSpeed ≤ 106
- The input represents a valid tree
Visualization
Tap to expand
Understanding the Visualization
1
Input
Tree network with weighted edges and signalSpeed requirement
2
Process
For each server as hub, count valid distance pairs to other servers
3
Output
Array showing connectable pairs count for each server as hub
Key Takeaway
🎯 Key Insight: In trees, paths from a central node to different subtrees never overlap, making pair counting efficient through DFS subtree exploration
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code