-
Firstly, we solve the case d = + ∞. In this case, we can forget all ai since they doesn't play a role anymore. Consider the tree is rooted at node 1. Let Fi be the number of valid sets contain node i and several other nodes in subtree of i("several" here means 0 or more). We can easily calculate Fi through Fj where j is directed child node of i: . Complexity: O(n).
-
General case: d ≥ 0. For each node i, we count the number of valid sets contain node i and some other node j such thatai ≤ aj ≤ ai + d (that means, node i have the smallest value a in the set). How? Start DFS from node i, visit only nodes jsuch that ai ≤ aj ≤ ai + d. Then all nodes have visited form another tree. Just apply case d = + ∞ for this new tree. We have to count n times, each time is O(n), so the overall complexity is O(n2). (Be craeful with duplicate counting)
Here is my code.