#P7108. 移花接木
移花接木
Description
The spirit tree’s original form can be viewed as a full -ary tree with height . The height is defined as the number of edges from the root node to a leaf node.
Affected by the decayed power, the spirit tree can only maintain the form of a full -ary tree with height exactly . To transform into this form, the spirit tree has two kinds of magic:
- Transplanting: choose an edge ( is the parent of ), remove this edge and the entire subtree rooted at .
- Grafting: choose an edge ( is the parent of ) and a node ( cannot be in the subtree of or a node that has been removed), and reattach the endpoint at of this edge to . This magic can only be used when the number of edges from the root node to is .
The spirit tree has limited accumulated magical power, so it must complete the transformation using the minimum number of spells. This is a long process: even the minimum number can be extremely large. You only need to compute the minimum number modulo .
Input Format
The first line contains the number of test cases .
The next lines each contain three integers , describing one test case.
Output Format
For each test case, output one integer per line, the answer modulo .
2
1 2 1
3 2 1
2
7
Hint
[Sample Explanation #1]
Below is the two-step transformation process for , , . The extremely tall redundant subtrees in the figure are replaced by ellipses.

It can be proven that the answer for this test case cannot be less than .
[Constraints and Notes]
This problem uses bundled tests. You must pass all test points in a Subtask to obtain the score for that Subtask.
- Subtask #1 (3 points): .
- Subtask #2 (4 points): .
- Subtask #3 (8 points): .
- Subtask #4 (8 points): .
- Subtask #5 (17 points): .
- Subtask #6 (15 points): . For each test point, there exist such that the testdata satisfy and .
- Subtask #7 (15 points): .
- Subtask #8 (30 points): no special restrictions.
All test points (except the samples) contain test cases, i.e. . Be sure to use fast I/O methods.
For all test cases, it is guaranteed that and .
Translated by ChatGPT 5
京公网安备 11011102002149号