#P6556. The Forest

The Forest

Description

Please note that the time limit for this problem is 5s!

Explorer A and Explorer B need to use light bulbs to light up this forest.

There are nn light bulbs, numbered 1,2,,n1, 2, \cdots, n. Explorer A uses n1n - 1 red ropes to connect them into a tree, and Explorer B uses n1n - 1 blue ropes to connect them into another tree.

At the beginning, all bulbs are off. Now we want to turn on some of the bulbs. Explorer A likes connected components, and Explorer B likes paths. They want to know: how many ways are there to turn on bulbs such that the turned-on bulbs form a connected component in A's tree, and form a path in B's tree?

Input Format

The first line contains an integer TT, meaning there are TT test cases. For each test case:

The first line contains an integer nn.

Lines 22 to nn, i.e. line i+1i + 1, contain two integers ai,bia_i, b_i, representing an edge in A's tree.

Lines n+1n + 1 to 2n12n - 1, i.e. line i+ni + n, contain two integers ci,dic_i, d_i, representing an edge in B's tree.

Output Format

Output TT lines. The ii-th line is the answer for the ii-th test case.

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

5
9
14

Hint

Sample Explanation:

Diagrams for the three test cases:

Sample 1:

Sample 2:

Sample 3:


For the first test case, the valid sets of bulbs to turn on are:

  • {1}\{1\};
  • {2}\{2\};
  • {3}\{3\};
  • {1,2}\{1, 2\};
  • {1,2,3}\{1, 2, 3\}.

Note that you cannot turn on the set {1,3}\{1, 3\}, because bulbs 11 and 33 do not form a connected component in A's tree. You also cannot turn on the set {2,3}\{2, 3\}, because bulbs 22 and 33 do not form a path in B's tree.

For the second test case, the valid sets of bulbs to turn on that contain at least two bulbs are:

  • {1,2}\{1, 2\};
  • {1,2,3}\{1, 2, 3\};
  • {1,2,3,4}\{1, 2, 3, 4\};
  • {1,2,3,4,5}\{1, 2, 3, 4, 5\}.

Clearly, all bulb sets of size 11 are valid, so the answer is 4+5=94 + 5 = 9.

Constraints and Notes:

For 20%20\% of the testdata, n50n \le 50, and it satisfies the special constraint XX.
For 40%40\% of the testdata, n3000n \le 3000, and it satisfies the special constraint XX.
For 70%70\% of the testdata, it satisfies the special constraint XX.
For 100%100\% of the testdata, T=3,1n105T = 3, 1 \le n \le 10^5.

Special constraint XX: ci=i,di=i+1c_i = i, d_i = i + 1, that is, B's tree is a path, and there is an edge between nodes with adjacent indices.

Translated by ChatGPT 5