KatInterview

Hub Node Pair Counting on a Weighted Tree with Divisible Distances

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphstreedfscounting

Last 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, a and b are three distinct machines;
  • the route length from h to a is divisible by k, and the route length from h to b is divisible by k;
  • the route from h to a and the route from h to b do not use any wire in common.

Compute, for every machine acting as the hub, the number of pairs it serves.

Input

  • links: a list of n - 1 triples [u, v, w], each describing an undirected wire of length w between machines u and v. The number of machines is n = 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 <= 1000
  • len(links) == n - 1
  • 0 <= u, v <= n - 1, u != v
  • 1 <= w <= 10^6
  • 1 <= 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 most n * (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.