Keeping the Tree Healthy
InterviewTime limit1sMemory limit1024 MB
Given a tree whose nodes are marked 1 (unhealthy) or 0, cut the fewest edges so every connected component has at most K unhealthy nodes, and print that count.
- Level
Medium6 of 10
- Topics
- Tree, Dynamic programming, Greedy, Sorting
- Solved
- No attempts yet
Problem
Yehwan likes playing with trees, so they built one out of tree branches. After some time, Yehwan noticed that some of the joints between branches are rotting. Yehwan wants to take a rose pruner and cut the fewest possible branches so that every connected component becomes healthy.
Call the points where branches meet nodes, and consider the graph formed by connecting nodes with edges (branches). Graph is a tree. A rotting node is called an unhealthy node. Yehwan considers a connected component healthy if it contains at most unhealthy nodes.

The figure above shows one way to split the tree into healthy parts when . (Red nodes are unhealthy nodes.)
Given the total number of nodes and the maximum number of unhealthy nodes in a connected component, print the minimum number of edges to remove so that every remaining connected component is healthy.
Input
The first line contains two integers and , separated by a space.
The second line contains integers , separated by spaces. For each , if node is an unhealthy node, and otherwise.
The next lines each contain two integers and , separated by a space. This means an edge exists between node and node .
Output
Print the minimum number of edges to remove so that every remaining connected component is healthy.
Constraints
- ,
- For each ,
- , ,
- All given numbers are integers.
- The given graph is a tree.