Strange Dream
Time limit1sMemory limit128 MB
Count ways to pick plates from boxes in a forward then backward pass so the recorded product is divisible by k, modulo l.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Number theory, Combinatorics
- Solved
- No attempts yet
Problem
Dumitru had a very strange dream: he was locked inside a room. In that room there were boxes, and each box contained exactly plates. Every plate has a single integer greater than or equal to written on it. There was also a note in the room with two integers and on it, describing the following task.
- Step 1: Take one plate from the first box, write the number on it into your notebook, change the number on that plate to , and put the plate back into the box. Then, in the same way, take one plate from the second box, then one from the third box, , up to and including the -th (last) box. Each time, take one plate from the current box, write its number in the notebook, change that plate's number to , and put it back.
- Step 2: After that, in the same way, take one plate from box , then one from box , , down to and including the second box. Each time, take one plate from the current box, write its number in the notebook, change that plate's number to , and put it back.
Let be the number of different ways of picking the plates as described above such that the product of all the numbers written in the notebook is divisible by . Because can be extremely large, compute the remainder of when divided by .
Input
The first line contains two integers and separated by a single space. The second line contains two integers and separated by a single space. Then follow lines, each containing integers separated by single spaces. The first of these lines holds the numbers written on the plates in the first box, the second line holds the numbers of the second box, and so on.
Output
Print a single integer: the remainder of when divided by .
Constraints
- Each number written on a plate is an integer between and inclusive.
Explanation
In the first example there are exactly ways of picking the plates so that the product of the numbers written in the notebook is divisible by . Two points are important.
- If in some box you pick the same plate in both Step 1 and Step 2, then its number was already changed to during Step 1, so the value written in the notebook during Step 2 is .
- Two ways are counted as different whenever the combination of chosen plate indices differs, even if the multiset of picked plate values is the same.