Cheats
Time limit10sMemory limit256 MB
Count the completion orders of a tree of prerequisites when up to k parent edges can be skipped to grandparents, with no two skipped edges adjacent.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Tree, Combinatorics
- Solved
- No attempts yet
Problem
Cosmo is playing a little known recent entry in the Legend of Zelda series, "Skyward Wind Mask of Twilight Time". In this game the player is the young adventurer Link and has to finish all objectives. Some objectives have to be finished before others. Every objective () has one prerequisite , and has to be finished before . Objective 1 has no prerequisite. The prerequisite relation has no cycles.
The game also hides cheats. There is one cheat for each objective (), and it lets Cosmo finish before its prerequisite . The order still cannot be broken completely. If the cheat for objective is used, no longer has to come after , but it still has to come after , the prerequisite of its prerequisite. If , objective 1 has no prerequisite, so can be finished at any point.
Cheats used too close to each other make the game behave unpredictably. If Cosmo uses the cheat for objective , he cannot use the cheat for , and he cannot use the cheat for any objective whose prerequisite is . Two objectives that the prerequisite relation links directly can never both be cheated. Two objectives that share the same prerequisite can both be cheated.
Cosmo wants to finish the game using at most cheats. Count the orders in which he can finish all objectives under these rules. An order is counted once even when several different sets of cheats produce it. The answer can be very large, so print it modulo .
Input
The input holds several test cases. Each test case begins with a line holding two integers and (, ). is the number of objectives and is the largest number of cheats Cosmo is willing to use. The next line holds space separated integers (), the prerequisites of objectives in that order. Objective 1 is skipped because it has no prerequisite. When this line is empty. The input ends with a line holding two zeros.
Output
For each test case print one line with the number of orders in which Cosmo can finish all objectives using at most cheats, modulo . Print no spaces and no blank lines between the answers.
Note
In the first example and the prerequisites are , , , . There are 12 orders that use no cheat, 12 that use the cheat for objective 4, 8 that use the cheat for objective 5, 3 that use the cheat for objective 2, and 3 that use the cheat for objective 3. The sum is 38.