Like other leading AI companies, ChatDOJ, Inc. is working to bring forward the day when AI models can improve themselves. First, however, the company needs to know how many tasks a model can complete on its own before calling a human.
ChatDOJ, Inc. has classified the tasks handled by the model into types, numbered through . Types through are repeat tasks that the model can return to when problems arise, and the rest are ordinary tasks.
The model processes one task at a time. After completing a task, it either calls a human and stops, or moves on to the next task, according to the given probabilities. These probabilities depend only on the type of task just completed.
When moving from an ordinary task to another ordinary task, the model must move to one with a larger number. A transition to a task with the same or a smaller number is possible only when the destination is a repeat task.
If the weight for moving from task to task after completing it is , that transition has probability . A transition absent from the weight list has weight . The probability of calling a human after task is .
Each query specifies the first task to process. Find the expected number of tasks the model completes before calling a human. Count both ordinary tasks and repeat tasks.
The first line contains the number of task types , the number of positive-weight transitions , the number of types of repeat tasks , the number of queries , and the common denominator of transition probabilities , separated by spaces.
The next lines describe the transitions. Each line contains integers , , and , separated by spaces. Each ordered pair occurs in at most one transition.
Print the answer to each query in the given order, one per line.
If the expectation is expressed as a fraction in lowest terms, print modulo .
Here, is the multiplicative inverse of modulo . The guarantees in the constraints ensure that this inverse always exists.
In the first example, only task is a repeat task. After completing task , the model calls a human with probability , returns to task with probability , and moves on to task with probability . After completing task , it always moves on to task . The expectations when starting from tasks through are , , , and , respectively.
The next lines contain the queries. Each line contains the number of the first task to process.
| 4 | 150 | . |
| 5 | 200 | No additional constraints. |
In the second example, tasks and are repeat tasks, and each always moves on to the task with the next number. After completing task , the model calls a human with probability ; otherwise, it returns to task or task .