This page is still under construction.

Parts of this page are still being built. What you see may change.

Sum of Scores

Time limit2sMemory limit512 MB

Summary
Find a non-empty vertex subset connected in both given trees whose score sum is maximized, with vertex counts up to 50.
Level

Hard8 of 10

Topics
Dynamic programming, Tree, Bit manipulation
Solved
No attempts yet

Problem

You are given two trees AA and BB, each with NN vertices. In both trees the vertices are numbered 0 to N−1N-1, and vertex ii has score sis_i. Scores are integers and may be negative.

Choose a non-empty subset S⊆{0,1,…,N−1}S \subseteq \{0, 1, \dots, N-1\} that satisfies both conditions below.

  • Keeping only the vertices of SS in tree AA leaves a connected subgraph.
  • Keeping only the vertices of SS in tree BB leaves a connected subgraph.

Among all such subsets SS, find the maximum value of the score sum ∑i∈Ssi\sum_{i \in S} s_i.

Input

The first line contains the number of vertices NN. (2≤N≤502 \le N \le 50)

Each of the next N−1N-1 lines contains one edge of tree AA as two integers aa and bb. (0≤a,b≤N−10 \le a, b \le N-1, a≠ba \ne b)

Each of the following N−1N-1 lines contains one edge of tree BB in the same format.

The last line contains NN integers s0,s1,…,sN−1s_0, s_1, \dots, s_{N-1} separated by spaces. (−1000≤si≤1000-1000 \le s_i \le 1000)

Both graphs in the input are trees.

Output

Print the maximum score sum on the first line.

Note

In the first example the score sum is largest for {0,1}\{0, 1\}. Picking {0,1,2}\{0, 1, 2\} does not leave a connected subgraph in tree BB.

Examples5

  1. Example 1

    Input
    4
    0 1
    0 3
    1 2
    0 1
    0 3
    3 2
    1000 24 100 -200
    
    Expected output
    1024
    
  2. Example 2

    Input
    4
    0 1
    0 3
    1 2
    0 1
    0 3
    3 2
    1000 24 100 200
    
    Expected output
    1324
    
  3. Example 3

    Input
    4
    0 1
    0 3
    1 2
    0 1
    0 3
    3 2
    -1000 24 100 200
    
    Expected output
    200
    
  4. Example 4

    Input
    7
    0 1
    0 2
    1 3
    1 4
    2 5
    2 6
    0 1
    0 2
    1 3
    1 4
    2 5
    2 6
    -3 2 2 -1 2 2 -1
    
    Expected output
    5
    
  5. Example 5

    Input
    7
    0 1
    0 2
    1 3
    1 4
    2 5
    2 6
    0 1
    0 2
    0 3
    0 4
    0 5
    0 6
    -3 2 2 -1 2 2 -1
    
    Expected output
    5