Tree Coloring
Time limit1sMemory limit512 MB
Given a rooted tree and a target color for each vertex, count the fewest subtree-recoloring operations (colors other than white) that reach the target.
- Level
Medium7 of 10
- Topics
- Tree, DFS, Greedy, Implementation
- Solved
- No attempts yet
Problem
There is a tree with vertices. The vertices are numbered from 1 to . The root of the tree is always vertex 1, and initially every vertex is colored white.
Coloring a vertex colors every vertex in its subtree with the same color. Colors do not blend; each coloring overwrites the previous one with the new color. White cannot be used for coloring.
Suppose there is a tree with 10 vertices, as in the figure below.

[Figure 1] A tree colored white
If vertex 3 is colored yellow, then vertices 5, 6, 8, 9, and 10 below it all become yellow.

[Figure 2] The tree after coloring vertex 3 yellow
Then, if vertex 5 is colored blue, then vertices 8, 9, and 10 below it all become blue.

[Figure 3] The tree after coloring vertex 5 blue
The input gives the tree and the color of each vertex. A color is given as a nonnegative integer, and the value 0 always means white.
Using only colors other than white, find the minimum number of colorings needed to color every vertex with its given color.
Input
The first line gives the number of vertices in the tree, .
The second line gives the color of each vertex from vertex 1 to vertex , separated by spaces.
Each of the next lines gives two connected vertices , , separated by spaces.
Only inputs for which every vertex can be colored are given.
Output
Print the minimum number of colorings needed to color every vertex with its desired color using only colors other than white.