Minimum Cost to Color a Tree
InterviewTime limit3sMemory limit512 MB
Paint each vertex of a tree white or black so that no two adjacent vertices are both black, at the minimum total cost.
- Level
Medium4 of 10
- Topics
- Tree, Dynamic programming, DFS
- Solved
- No attempts yet
Problem
A tree has vertices and edges. The vertices are numbered from 0 to , and vertex 0 is the root. The edges have no weights.
Each vertex of is painted either white or black. Two adjacent vertices cannot both be black. In other words, each pair of adjacent vertices must be colored white and black, black and white, or white and white.
Each vertex has a cost for painting it white and a cost for painting it black. Find the minimum total cost to color all vertices of .
Input
The first line contains the number of vertices .
Each of the next lines contains one edge, given as a parent vertex and a child vertex , separated by a space.
Each of the next lines gives the cost of painting one vertex, starting from vertex 0 up to vertex . Each line contains the white cost and the black cost , separated by a space.
Output
Print the minimum cost to color every vertex of on the first line.
Constraints
- ,
- The graph formed by the edges is a tree.
- , and and are positive integers.