Triangle Tree
Time limit2sMemory limit2048 MB
Given a rooted tree, sum the number of integer side lengths x that form a non-degenerate triangle over all pairs of vertices where neither is an ancestor of the other.
- Level
Medium6 of 10
- Topics
- Tree, DFS, Sorting, Prefix sum
- Solved
- No attempts yet
Statement
One day, a giant tree grew in the countryside. Little John, with his childhood eagle, decided to make it his home. Little John will build a structure on the tree with galvanized square steel. However, little did he know, he could not build what is physically impossible.
You are given a rooted tree with vertices, rooted at vertex . A pair of vertices is called a good pair if is not an ancestor of and is not an ancestor of . For any two vertices, is the number of edges on the unique simple path from to , and is their lowest common ancestor.
The function is defined as follows.
- If is a good pair, is the number of distinct integers for which a non-degenerate triangle exists with side lengths , , and .
- Otherwise, .
Compute .
1 A tree is a connected graph without cycles. A rooted tree is a tree in which one vertex is designated as the root.
2 An ancestor of vertex is any vertex on the simple path from to the root, excluding itself but including the root. The root has no ancestors.
3 A triangle with side lengths , , is non-degenerate when , , and .
Input
The first line contains the number of test cases (). Each test case is given as follows.
The first line of each test case contains a single integer ().
Each of the next lines contains two integers and (, ), the two vertices joined by an edge. The given edges form a tree.
The sum of over all test cases does not exceed .
Output
For each test case, output the answer on a separate line.
Hints
In the first test case, the only good pair with is . Here is , and both distances are . For side lengths and , the only valid is , so the answer for the first test case is .
The second test case has no good pair, so the answer is .
In the third test case, the good pairs with are the following.
- : is , and the distances are and . The only possible is .
- : is , and the distances are and . The only possible is .
- : is , and the distances are and . The only possible is .
- : is , and the distances are and . The only possible is .
So the answer for the third test case is .