Two Trees
Time limit2sMemory limit512 MB
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 vertices. In both trees the vertices are numbered through , and the same number refers to the same vertex.
Vertex has score .
Choose a subset of 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 , so the answer is never negative.
Input
The first line contains the number of vertices ().
Each of the next lines contains one edge of the first tree, given as the numbers of the two vertices it joins.
Each of the following lines contains one edge of the second tree in the same format.
The last line contains the scores separated by spaces ().
Output
Print the largest sum of scores on the first line.
Hint
In the first example, forms a connected subgraph in both trees. does not. In the second tree vertex is joined only to vertex , and vertex is not in the set.