Wind of Change 2020
Time limit12sMemory limit1024 MB
Given two weighted trees on N vertices (edge weights may be negative), output one integer: the answer defined by the maximum distance over pairs of vertices in T1.
- Level
Medium6 of 10
- Topics
- Tree, DFS, Dynamic programming
- Solved
- No attempts yet
Problem
There is a tree with vertices. Each vertex of is numbered from 1 to , and each edge has an integer weight (which may be negative). The maximum distance between two vertices of is called the diameter of the tree. The two vertices may be the same vertex.
Gu Jae-hyeon, a student who met this problem in a lab session, came up with the following approach. Root the tree at vertex 1. Then the distance between two vertices is
Here is the distance from the root to vertex in , and is the lowest common ancestor of and in . Gu uses a Sparse Table to find an LCA in . So by taking the maximum of this value over all , the problem can be solved in .
Input
The first line contains the number of vertices of both trees ().
The next lines each contain three integers . This means that tree has an edge of weight connecting vertices and (, ).
The next lines each contain three integers . This means that tree has an edge of weight connecting vertices and (, ).
Output
Print one integer, the answer to the problem.