#ds1005. 树的重心
树的重心
Tree Centroid
Problem Source
CSP-S 2019
Problem Description
Xiao Jiandan is studying discrete mathematics. Today's topic is graph theory basics, and he wrote down two notes in class:
- A tree of size consists of nodes and undirected edges, and any two nodes are connected by exactly one simple path. Deleting a node and its incident edges from a tree splits it into several subtrees; deleting an edge (keeping its endpoints) splits the tree into exactly two subtrees.
- For a tree of size and any node in it, is called a centroid of the tree if and only if, after deleting and its incident edges, every resulting subtree has size at most (where is the floor function). A tree with at least one node has either or centroids.
After class, the teacher gives Xiao Jiandan a tree of size , with nodes numbered from to . His homework is to compute, for with every single edge removed, the sum of the centroid numbers of the two resulting subtrees. That is:
$$\sum_{(u,v) \in E} \left( \sum_{\substack{1 \le x \le n \\ \text{and } x \text{ is a centroid of } S_u'}} x + \sum_{\substack{1 \le y \le n \\ \text{and } y \text{ is a centroid of } S_v'}} y \right)$$In the formula, is the edge set of tree , and is an edge connecting node and node . and denote the two subtrees into which is split after removing edge , containing node and node respectively.
Xiao Jiandan finds the homework not simple at all, so he asks you for help.
Input Format
This problem contains multiple test cases.
The first line contains an integer (), the number of test cases.
For each test case:
- The first line contains an integer (), the size of tree .
- The next lines each contain two space-separated integers , an edge of the tree.
Output Format
Output lines in total. The -th line contains one integer: for the tree given in the -th test case, the sum of the centroid numbers of the two subtrees split by removing every single edge.
Sample Input
2
5
1 2
2 3
2 4
3 5
7
1 2
1 3
1 4
3 5
3 6
6 7
Sample Output
32
56
Sample Explanation
For the first test case:
- Removing edge : the subtree containing node has centroid ; the subtree containing node has centroids .
- Removing edge : the subtree containing node has centroid ; the subtree containing node has centroids .
- Removing edge : the subtree containing node has centroids ; the subtree containing node has centroid .
- Removing edge : the subtree containing node has centroid ; the subtree containing node has centroid .
So the answer is .