The Older We Are, The Worse It Hurts

Time limit2sMemory limit512 MB

Summary
Root the tree anywhere and order each node's children so that the weighted sum of DFS discovery times is minimized; output that minimum.
Level

Hard8 of 10

Topics
Tree, DFS, Greedy, Sorting
Solved
No attempts yet

Problem

You are given a tree with n vertices. Each vertex i has a weight ai.

You traverse the whole tree starting at an arbitrary vertex and moving along the edges so that each edge is traversed exactly once in each direction. In other words, you perform a depth-first search traversal, choosing the starting vertex and the order of outgoing edges at each vertex arbitrarily. Write down the list of all vertices, (v1, v2, . . . , vn), sorted by the time you first arrive at them. You get a penalty of ∑i · avi.

Your goal is to minimize the penalty. Note that (v1, v2, . . . , vn) is a permutation of (1, 2, . . . , n), and v1 is the vertex you start from.

Input

The first line contains the only integer n (1 ≤ n ≤ 200 000) denoting the number of vertices. The next n−1 lines contain edge descriptions: the i-th of them contains two integers ui and vi (1 ≤ ui, vi ≤ n) denoting the edge between ui and vi. The next line contains n space-separated integers ai (1 ≤ ai ≤ 200 000).

The given edges form a tree.

Output

Print a single line with a single integer on it: the minimum possible penalty.

Examples2

  1. Example 1

    Input
    3
    1 2
    1 3
    1 2 3
    
    Expected output
    11
    
  2. Example 2

    Input
    5
    1 2
    1 3
    3 4
    3 5
    5 4 3 2 1
    
    Expected output
    35