Count the nonempty connected vertex subsets of a weighted tree whose maximum minus minimum weight is at most d.
Hard8TreeDFSDivide and conquerDynamic programmingNo attempts yetTime limit3sMemory limit512 MB
Description
Examples2
Problem
There is a tree with N vertices. Vertex i carries a weight a(i). Given one integer d, a set S of tree vertices is a "possible set" when it satisfies all of the following conditions.
S is not empty.
The vertices in S are connected. That is, for any two vertices u and v in S, every vertex on the path joining them belongs to S.
maxu∈Sa(u)−minv∈Sa(v)≤d
Write a program that counts the possible sets S. The count can be very large, so print it modulo 109+7.
Input
The first line contains d and N. (0≤d≤20000, 1≤N≤20000)
The second line contains N integers, a(1) through a(N) in order. (1≤a(i)≤20000)
Each of the next N−1 lines contains two integers u and v, an edge of the tree. (1≤u,v≤N)
Output
Print the number of possible sets modulo 109+7 on the first line.
Hint
In the first example the eight possible sets are {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}.