Easily Happy Tree
Time limit2sMemory limit512 MB
Delete the fewest leaves from a rooted tree so that no remaining vertex has a descendant farther away than that descendant's own limit a_u.
- Level
Hard8 of 10
- Topics
- Tree, DFS, Greedy, Dynamic programming
- Solved
- No attempts yet
Problem
A tree has vertices numbered 1 through , and vertex 1 is the root. Every vertex and every edge carries one number. Minju came back from an algorithm camp, visited a forest, and looked at this tree. Some of its vertices looked sad to her. The camp is over and she is in a good mood, so she wants to cut a few vertices and make the tree happy.
Vertex is sad when the subtree rooted at holds at least one vertex with . Here is the number written on vertex , and is the sum of the numbers written on the edges along the path from to .
Minju cannot lift anything heavier than a keyboard, so she can cut only a leaf. A leaf is a vertex with no child, that is, a vertex whose only neighbor is its parent. Vertex 1 counts as a leaf only when a single vertex is left in the tree. Cutting a leaf can turn its parent into a new leaf, and that vertex can then be cut too.
Find the smallest number of vertices Minju has to cut so that no sad vertex is left.
In the picture below, 1) is the starting tree, and 2) through 6) are the five vertices that get cut, in order.

Input
The first line contains the number of vertices ().
The second line contains the numbers written on vertices 1 through , in that order ().
Each of the next lines describes one edge. The two integers and on the -th of those lines (, ) mean that vertex is joined to vertex by an edge whose number is . When the tree is rooted at vertex 1, vertex is not guaranteed to be the parent of vertex . The edges always form a tree.
Output
Print the smallest number of leaves that have to be cut to make the tree happy.