Under construction

Still being built. Things may change

Minimum Cost to Color a Tree

Interview

Time limit3sMemory limit512 MB

Summary
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 TT has nn vertices and n−1n - 1 edges. The vertices are numbered from 0 to n−1n - 1, and vertex 0 is the root. The edges have no weights.

Each vertex of TT 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 TT.

Input

The first line contains the number of vertices nn.

Each of the next n−1n - 1 lines contains one edge, given as a parent vertex pp and a child vertex cc, separated by a space.

Each of the next nn lines gives the cost of painting one vertex, starting from vertex 0 up to vertex n−1n - 1. Each line contains the white cost ww and the black cost bb, separated by a space.

Output

Print the minimum cost to color every vertex of TT on the first line.

Constraints

  • 2≤n≤1000002 \le n \le 100000
  • 0≤p,c≤n−10 \le p, c \le n - 1, p≠cp \ne c
  • The graph formed by the edges is a tree.
  • 1≤w,b≤1000001 \le w, b \le 100000, and ww and bb are positive integers.

Examples1

  1. Example 1

    Input
    8
    0 1
    0 2
    1 3
    1 4
    2 5
    2 6
    6 7
    10 20
    10 30
    10 100
    100 50
    50 50
    10 50
    10 50
    70 100
    
    Expected output
    220