This page is still under construction.

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

Two Trees

Time limit2sMemory limit512 MB

Summary
Pick a vertex subset connected in both of two trees to maximize the total score, with the empty set allowed.
Level

Hard8 of 10

Topics
Tree, DFS, Dynamic programming
Solved
No attempts yet

Problem

You are given two trees, each with NN vertices. In both trees the vertices are numbered 00 through N−1N-1, and the same number refers to the same vertex.

Vertex ii has score SiS_i.

Choose a subset of {0,1,…,N−1}\{0, 1, \dots, N-1\} that satisfies both of these conditions.

  • Keeping only the chosen vertices in the first tree leaves a connected subgraph.
  • Keeping only the chosen vertices in the second tree leaves a connected subgraph.

Write a program that finds the largest sum of scores over all such subsets. The empty subset is allowed and its sum is 00, so the answer is never negative.

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 the first tree, given as the numbers of the two vertices it joins.

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

The last line contains the scores S0,S1,…,SN−1S_0, S_1, \dots, S_{N-1} separated by spaces (−1000≤Si≤1000-1000 \le S_i \le 1000).

Output

Print the largest sum of scores on the first line.

Hint

In the first example, {0,1}\{0, 1\} forms a connected subgraph in both trees. {0,1,2}\{0, 1, 2\} does not. In the second tree vertex 22 is joined only to vertex 33, and vertex 33 is not in the set.

Examples4

  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
    0
    
  4. Example 4

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