Mysterious Button
Time limit8sMemory limit512 MB
For each query, count the button press sequences from room 1 that end by escaping from room d and collect exactly e coins.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Matrix, Graph
- Solved
- No attempts yet
Problem
You decide to earn coins in a dungeon on the outskirts of a town. The dungeon has rooms, numbered 1 to . It contains three kinds of mysterious buttons: coin buttons, escape buttons, and warp buttons.
- Each room has exactly one coin button. You can press a coin button any number of times, and each press gives you 1 coin.
- Each room has exactly one escape button. Pressing it leaves the dungeon immediately and ends the adventure.
- There are warp buttons in total. The -th warp button is in room . Pressing it teleports you to room and gives you coins. Here and . A room may have several warp buttons, and some rooms may have none.
You can move between rooms only by pressing buttons, and you cannot press several buttons at once. All buttons are distinguishable from each other.
You have explored this dungeon times. If your memory is correct, the -th adventure started in room 1 and ended by pressing the escape button in room , collecting exactly coins in total. For each adventure, find the number of ways to press buttons that match this record. Two button sequences are different if they have different total numbers of presses, or if there is some integer such that the -th pressed button differs. Since the answer can be large, print it modulo .
Your memory may be wrong, in which case no such sequence exists. Then print 0.
Input
The input consists of multiple datasets in the following format.
N M
a1 b1 c1
a2 b2 c2
...
aM bM cM
Q
d1 e1
d2 e2
...
dQ eQ
The first line of each dataset has and , with . The next lines describe the warp buttons. Line contains , , and , with and . Line contains , with . The next lines each contain and , with and .
The input ends with a line containing two zeros. There are at most 50 datasets in total.
Output
For each dataset, output lines. Line contains the number of ways to press buttons that start in room 1, end by pressing the escape button in room , and collect exactly coins in total, modulo .