The Safe
Time limit4sMemory limit128 MB
Count the ordered sequences of exactly R dial turns that leave target k at the top, modulo 1000033.
- Level
Hard8 of 10
- Topics
- Matrix, Dynamic programming, Combinatorics
- Solved
- No attempts yet
Problem
These days nothing left out in the open is safe, and Hektor's Ukemon card collection is no exception: tomorrow his younger cousin Olek comes to visit. To keep the collection he spent so long building out of harm's way during the visit, Hektor bought a safe just for the occasion and locked the cards inside.
The safe's lock is a round dial. The numbers through are printed around it clockwise, with at the very top. The dial can be turned only in one of preset ways; each way turns it a fixed number of steps to the left or to the right. The safe opens when, after exactly turns, the number is at the top.
Let be the number currently at the top (so before any turn). A left turn written L x changes the top number to , and a right turn written P x changes it to . The turns are applied one after another.
Hektor wants to gauge how secure the safe is, so for several targets he needs to know how many different ordered sequences of turns (each turn chosen from the available ways) leave the number at the top.
Input
The first line contains a natural number (), the number of test sets. The sets follow one after another.
For each set, the first line contains two space-separated natural numbers and (). Each of the next lines describes one allowed turn: a letter, L (left) or P (right), giving the direction, then a space, then a natural number () giving how many steps it turns. All turns are pairwise different.
The next line contains a natural number (), the number of pairs to check. Each of the following lines contains two positive integers () and ().
Output
For each pair , print on its own line a single non-negative integer: the number of different ordered sequences of turns that open the safe (that is, leave at the top), taken modulo .