C is at an empty field with dimensions, each dimension has size of , meaning that all positions in the field should satisfy the condition .
C is planning to walk for the next days, starting from a new position every day. In other words, he will walk from every position in the field. Every day, he will walk in a planned route consisting of repeating steps, denoted by and meaning that he will walk from to . C will repeat the route until he leaves the field. That is, if C is still in the field after steps, he will go back to step and start all over again.
Find the number of steps C took after days.
Input Specification
The first line contains two integers , denoting the number of steps in C's route and the number of dimensions of the field. The next line contains integers , denoting the sizes of dimensions of the field. The next lines contain two integers on every line, denoting , as mentioned above.
Output Specification
Output one integer denoting the answer modulo .
If C will be stuck in the field forever on one day, output -1
.
Sample Input 1
3 2
3 3
1 1
2 -1
1 1
Sample Output 1
21
Starting at will take steps, starting at will take steps, starting at will take steps.
Starting at will take steps, starting at will take steps, starting at will take steps.
Starting at will take steps, starting at will take steps, starting at will take steps.
The answer would be .
Sample Input 2
5 4
6 8 6 5
3 1
2 1
1 1
2 1
2 -1
Sample Output 2
10265
Constraints
For all test cases, , , , .
For partials, refer to the table below.
Test Case | |||
---|---|---|---|
1~3 | |||
4~6 | |||
7~8 | |||
9~12 | |||
13~16 | |||
17~20 |
Comments