You are given an unrooted weighted tree of n servers numbered 0 to n - 1, described by an array edges where edges[i] = [a_i, b_i, weight_i] is a bidirectional edge of weight weight_i between servers a_i and b_i, and an integer signal_speed. The distance between two servers is the sum of the edge weights on the path between them.
Two servers a and b are connectable through a server c when all of the following hold:
-
a < b
,
a != c
and
b != c
.
-
The distance from
c
to
a
is divisible by
signal_speed
.
-
The distance from
c
to
b
is divisible by
signal_speed
.
-
The path from
c
to
a
and the path from
c
to
b
share no edge.
Return an array count of length n where count[i] is the number of server pairs that are connectable through server i.
Function Signature
def count_pairs_of_connectable_servers(edges: list[list[int]], signal_speed: int) -> list[int]:
Rules
-
The number of servers is
n = len(edges) + 1
, and
edges
always forms a valid tree on servers
0
to
n - 1
.
-
Pairs are unordered. Because of the
a < b
condition, each pair of servers counts at most once for a given
c
.
Constraints
-
2 <= n <= 1000
-
len(edges) == n - 1
-
edges[i]
has length 3
-
0 <= a_i, b_i < n
-
1 <= weight_i <= 10^6
-
1 <= signal_speed <= 10^6
Examples
Input: edges = [[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]], signal_speed = 1
Output: [0, 4, 6, 6, 4, 0]
The tree is the path 0-1-2-3-4-5, and with a speed of 1 every distance is divisible. Server 2 has {0, 1} on one side and {3, 4, 5} on the other, and any server from one side with any server from the other gives edge-disjoint paths from 2, so it gets 2 * 3 = 6. Server 1 gets 1 * 4 = 4 the same way, and the end servers 0 and 5 have only one side, so they get 0.
Input: edges = [[0,6,3],[6,5,3],[0,3,1],[3,2,7],[3,1,6],[3,4,2]], signal_speed = 3
Output: [2, 0, 0, 0, 0, 0, 2]
From server 0 the distances are 3 to server 6, 6 to server 5, 1 to server 3, 8 to server 2, 7 to server 1 and 3 to server 4, so servers 4, 5 and 6 qualify. The pairs (4, 5) and (4, 6) have edge-disjoint paths from 0, while (5, 6) does not because both paths use the edge 0-6. Server 6 likewise gets the pairs (0, 5) and (4, 5), and every other server gets 0.
Input: edges = [[0,1,2],[0,2,4],[0,3,3]], signal_speed = 2
Output: [1, 0, 0, 0]
From server 0, servers 1 and 2 are at even distances 2 and 4 along different edges, so (1, 2) is the only pair (server 3 is at the odd distance 3). From server 1, servers 0 and 2 are at distances 2 and 6, but both paths start with the edge 1-0, so the pair does not count.