Tropical Garden
Time limit5sMemory limit256 MB
Count starting ponds whose deterministic non-backtracking walk (prefer the most beautiful unused-at-previous-step walkway) reaches pond P after exactly K steps, for many K.
- Level
Hard9 of 10
- Topics
- Graph, Simulation, Math, Number theory
- Solved
- No attempts yet
Problem
The botanist Chulsoo visits a huge tropical garden together with several school classes. The garden has ponds, numbered through , and walkways, numbered through . Each walkway connects two distinct ponds and can be traversed in both directions. Every pond has at least one walkway attached to it, and between any two ponds there is at most one walkway.
The walkways are numbered in decreasing order of beauty: for every , walkway is more beautiful than walkway . Because Chulsoo is a botanist, no two walkways are ever equally beautiful.
Chulsoo and the students move according to the following rule. At the current pond they always take the most beautiful attached walkway. However, if that walkway is exactly the one they used on the previous move, they take the second most beautiful walkway instead. The only exception is when the current pond has just one attached walkway: there is no second choice, so they reuse the walkway they just arrived on. (At the start no walkway has been used yet, so they always leave along the most beautiful walkway.)
This movement rule is deterministic: once a starting pond is fixed, the entire route is uniquely determined.
The students want to have lunch at the fine restaurant next to pond . Each class becomes hungry after passing exactly walkways, and at that moment they must be standing at pond . The value of may differ between classes.
Treating each of the ponds as a possible starting pond, determine how many distinct routes end at pond after using exactly walkways. Each starting pond produces exactly one route, so this equals the number of such starting ponds. A route may pass through pond earlier, but immediately after the -th walkway it must be at .
Answer this for classes, that is, for values of .
Input
The first line contains three integers , , and separated by spaces.
Each of the next lines describes one walkway: line (for ) contains the numbers of the two ponds joined by walkway . The walkways are given in order of beauty, most beautiful first.
The next line contains the number of classes , and each of the following lines contains one value of .
Output
For each class, print on its own line the number of distinct routes (starting ponds) that reach pond using exactly walkways, in the same order as the input. Print if no such route exists.