P27502 [AtCoder] Bonsai Grafting
普及+
题目描述

Problem Description

Takahashi has purchased two bonsai trees and is trying to graft them together at one point.

Each bonsai can be represented as a tree with $N$ vertices for tree $A$ and $M$ vertices for tree $B$. The edges of tree $A$ connect vertex $p_{A_i}$ and vertex $q_{A_i}$ $(1 \leq i \leq N-1)$. The edges of tree $B$ connect vertex $p_{B_i}$ and vertex $q_{B_i}$ $(1 \leq i \leq M-1)$ (note that vertex $i$ in tree $A$ and vertex $i$ in tree $B$ are different vertices).

Consider creating a single tree with $N+M$ vertices by connecting one vertex from tree $A$ and one vertex from tree $B$ with an edge. There are a total of $NM$ ways to choose the vertices. Calculate the diameter (the maximum number of edges between any two points) for each of these $NM$ trees and find the sum of these diameters.

Input Format

The input is given from the standard input in the following format:

$N$ $p_{A_1}$ $q_{A_1}$ : $p_{A_{N-1}}$ $q_{A_{N-1}}$ $M$ $p_{B_1}$ $q_{B_1}$ : $p_{B_{M-1}}$ $q_{B_{M-1}}$

Output Format

Output the sum of the diameters of the $NM$ trees.

Sample Input and Output

Sample Input #1

4
1 2
2 3
3 4
2
1 2

Sample Output #1

36

Sample Input #2

5
1 2
1 3
1 4
1 5
3
1 2
2 3

Sample Output #2

67

Notes/Hints

Constraints

  • $2 \leq N, M \leq 10^5$
  • $1 \leq p_{A_i}, q_{A_i} \leq N$ $(1 \leq i \leq N-1)$
  • $1 \leq p_{B_i}, q_{B_i} \leq M$ $(1 \leq i \leq M-1)$
  • The two given graphs are each trees.
  • All inputs are integers.

Sample Explanation 1

For example, if vertex $2$ of $A$ and vertex $1$ of $B$ are connected with a new edge to form a tree with $N+M$ vertices, the diameter will be $4$.

输入格式

见题面 Input 部分

输出格式

见题面 Output 部分

样例输入
4 1 2 2 3 3 4 2 1 2
样例输出
36