Number of Good Service Paths

You manage the routing layer of a distributed platform. The service topology is a tree: n services numbered from 0 to n - 1, connected by exactly n - 1 undirected links, with every pair of services reachable and no cycles. Service i runs at an integer load level given by loads[i].

A route starts at some service s and ends at some service t, where s may equal t. Define the route threshold as loads[s]. A route is called good when both of these hold:

  • The endpoints share one load level, meaning loads[s] == loads[t].
  • No service on the route exceeds the route threshold, meaning every intermediate service has a load level less than or equal to loads[s].

Every single service counts as a good route on its own. Routes are undirected, so the pair {s, t} describes one distinct route, and two routes are different whenever their endpoint pairs differ. Return the number of distinct good routes in the topology.

Examples
Input: [[1,2,2,3,2],[[0,1],[1,2],[2,3],[2,4]]]
Output: 8
Hints

Number of Good Service Paths

You manage the routing layer of a distributed platform. The service topology is a tree: `n` services numbered from `0` to `n - 1`, connected by exactly `n - 1` undirected links, with every pair of services reachable and no cycles. Service `i` runs at an integer load level given by `loads[i]`.