Hub Node Pair Counting on a Weighted Tree with Divisible Distances
Trees & GraphsAuto-graded · 20 test casesLast updated
Count, for each node of a weighted tree, the unordered pairs of other nodes at distances divisible by k and lying in different branches around that node.
You are given a network of n machines labeled 0 to n - 1. The machines are linked by exactly n - 1 wires so that the network is a tree: between any two machines there is exactly one route. Each wire has a positive integer length.
Pick a machine h and call it the hub. An unordered pair of machines {a, b} is served by h if:
h,aandbare three distinct machines;- the route length from
htoais divisible byk, and the route length fromhtobis divisible byk; - the route from
htoaand the route fromhtobdo not use any wire in common.
Compute, for every machine acting as the hub, the number of pairs it serves.
Input
links: a list ofn - 1triples[u, v, w], each describing an undirected wire of lengthwbetween machinesuandv. The number of machines isn = len(links) + 1.k: the divisor used for the route-length test.
Output
Return a list answer of length n, where answer[h] is the number of unordered pairs served by machine h. A pair {a, b} is the same as {b, a} and is counted once for a given hub.
The route length between two machines is the sum of the wire lengths on the unique route between them.
Constraints
2 <= n <= 1000len(links) == n - 10 <= u, v <= n - 1,u != v1 <= w <= 10^61 <= k <= 10^6- The wires always form a valid tree (connected, acyclic, no duplicate wires).
- Every route length is at most
999 * 10^6; every count is at mostn * (n - 1) / 2.
Examples
Example 1
Input: count_served_pairs([[0, 1, 2], [1, 2, 2], [2, 3, 4]], 2)
Output: [0, 2, 2, 0]
Example 2
Input: count_served_pairs([[0, 1, 3], [0, 2, 6], [0, 3, 4], [3, 4, 2]], 3)
Output: [3, 0, 0, 0, 0]
Hints
Hint 1
Fix one hub and imagine deleting it from the tree. The tree falls apart into one piece per wire attached to the hub. How does the 'no shared wire' condition relate to these pieces?
Hint 2
Two routes from the hub share a wire exactly when both machines are in the same piece. So you only need, for each piece, the number of machines whose distance from the hub is divisible by k, then combine counts across different pieces.
Hint 3
To combine piece counts without a double loop, keep a running total of earlier counts and add count * seen for each new piece, or use (T^2 - sum of squares) / 2. Remember the hub itself (distance 0) must never be counted, and with n up to 1000 an O(n^2) approach (one traversal per hub) is fine.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Fix a hub h and remove it from the tree. What remains splits into one component (a branch) for each wire attached to h. Every other machine lies in exactly one branch, and its route from h always starts with that branch's wire.
This turns the "no shared wire" rule into a simple one:
- Two machines in different branches leave
hthrough different wires and then travel through disjoint parts of the tree, so their routes share no wire. - Two machines in the same branch both start with the same wire, so they do share one.
So a pair is served by h exactly when its two machines are in different branches and both have a route length from h divisible by k.
For each hub:
- For each neighbor
nb(wire lengthw), run an iterative DFS into that branch, starting atnbwith distancewand never stepping back toward the hub. Count the machines whose distance is divisible byk; call thiscnt. - Maintain
seen, the number of qualifying machines in previous branches. The new branch contributescnt * seenpairs; then addcnttoseen. - Store the accumulated total as the answer for
h.
Hubs with fewer than two wires have a single branch (or none) and contribute 0, so they are skipped.
Why it is correct
- Distinct machines: every DFS starts at a neighbor and never returns to the hub, so the hub (distance 0, which would pass every divisibility test) is never counted. Machines from different branches are automatically different.
- Divisibility: distances are accumulated exactly along the unique tree path, so the modulus test uses the true route length.
- Disjoint routes: by the branch argument, "no shared wire" is equivalent to "different branches".
- Counting: each unordered qualifying pair in different branches is counted exactly once, when the later of its two branches is processed (
cnt * seen).
Complexity
- Time: O(n^2). For each hub, the branch traversals together visit every other machine once. With
n <= 1000this is about 10^6 steps. - Space: O(n) for the adjacency list and the traversal stack.
Since k can be as large as 10^6, tracking residues per node in an array does not help, so the quadratic approach is appropriate here. The traversal is iterative to avoid recursion limits on chain-shaped trees.
Reference solution
from typing import List
def count_served_pairs(links: List[List[int]], k: int) -> List[int]:
n = len(links) + 1
adj = [[] for _ in range(n)]
for u, v, w in links:
adj[u].append((v, w))
adj[v].append((u, w))
answer = [0] * n
for hub in range(n):
if len(adj[hub]) < 2:
continue
seen = 0
pairs = 0
for nb, w in adj[hub]:
cnt = 0
stack = [(nb, hub, w)]
while stack:
x, parent, dist = stack.pop()
if dist % k == 0:
cnt += 1
for y, wy in adj[x]:
if y != parent:
stack.append((y, x, dist + wy))
pairs += cnt * seen
seen += cnt
answer[hub] = pairs
return answer