#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:

  1. A tree of size nn consists of nn nodes and n−1n - 1 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.
  2. For a tree of size nn and any node cc in it, cc is called a centroid of the tree if and only if, after deleting cc and its incident edges, every resulting subtree has size at most ⌊n/2⌋\lfloor n/2 \rfloor (where ⌊x⌋\lfloor x \rfloor is the floor function). A tree with at least one node has either 11 or 22 centroids.

After class, the teacher gives Xiao Jiandan a tree SS of size nn, with nodes numbered from 11 to nn. His homework is to compute, for SS 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, EE is the edge set of tree SS, and (u,v)(u, v) is an edge connecting node uu and node vv. Su′S_u' and Sv′S_v' denote the two subtrees into which SS is split after removing edge (u,v)(u, v), containing node uu and node vv 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 TT (1≤T≤51 \le T \le 5), the number of test cases.

For each test case:

  • The first line contains an integer nn (1≤n≤3×1051 \le n \le 3 \times 10^5), the size of tree SS.
  • The next n−1n - 1 lines each contain two space-separated integers ui,viu_i, v_i, an edge of the tree.

Output Format

Output TT lines in total. The ii-th line contains one integer: for the tree given in the ii-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 (1,2)(1, 2): the subtree containing node 11 has centroid {1}\{1\}; the subtree containing node 22 has centroids {2,3}\{2, 3\}.
  • Removing edge (2,3)(2, 3): the subtree containing node 22 has centroid {2}\{2\}; the subtree containing node 33 has centroids {3,5}\{3, 5\}.
  • Removing edge (2,4)(2, 4): the subtree containing node 33 has centroids {2,3}\{2, 3\}; the subtree containing node 44 has centroid {4}\{4\}.
  • Removing edge (3,5)(3, 5): the subtree containing node 33 has centroid {2}\{2\}; the subtree containing node 55 has centroid {5}\{5\}.

So the answer is 1+2+3+2+3+5+2+3+4+2+5=321 + 2 + 3 + 2 + 3 + 5 + 2 + 3 + 4 + 2 + 5 = 32.