Under construction

Still being built. Things may change

Minimum cost to color a tree

Interview

Time limit1sMemory limit512 MB

Summary
Given a tree rooted at 0 with white and black costs per vertex, find the minimum total cost so that every adjacent pair has different colors.
Level

Easy3 of 10

Topics
Dynamic programming, Tree
Solved
No attempts yet

Problem

There is a tree TT with nn vertices and n−1n-1 edges. Vertex numbers run from 0 to n−1n-1, and vertex 0 is the root. The edges have no weights.

You want to color each vertex of TT either white or black. Two adjacent vertices must have different colors. Each vertex has a cost for coloring it white and a cost for coloring 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 as two integers, the parent vertex pp and the child vertex cc, separated by a space.

Each of the next nn lines gives the costs for one vertex, in order from vertex 0 to vertex n−1n-1. Each line has two integers ww and bb, separated by a space. ww is the cost to color the vertex white, and bb is the cost to color it black.

Output

Print the minimum cost to color all vertices of tree TT on the first line.

Constraints

  • 2≤n≤100,0002 \le n \le 100{,}000
  • 0≤p,c≤n−10 \le p, c \le n-1, p≠cp \ne c
  • The edges form a tree.
  • 1≤w,b≤100,0001 \le w, b \le 100{,}000, 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
    310