This page is still under construction.

Parts of this page are still being built. What you see may change.

The Safe

Time limit4sMemory limit128 MB

Summary
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 11 through NN are printed around it clockwise, with 11 at the very top. The dial can be turned only in one of MM preset ways; each way turns it a fixed number of steps to the left or to the right. The safe opens when, after exactly RR turns, the number kk is at the top.

Let vv be the number currently at the top (so v=1v = 1 before any turn). A left turn written L x changes the top number to ((v−1+x) mod N)+1((v - 1 + x) \bmod N) + 1, and a right turn written P x changes it to ((v−1−x) mod N)+1((v - 1 - x) \bmod N) + 1. 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 RR turns (each turn chosen from the MM available ways) leave the number kk at the top.

Input

The first line contains a natural number ZZ (Z=1Z = 1), the number of test sets. The sets follow one after another.

For each set, the first line contains two space-separated natural numbers NN and MM (1≤N,M≤20001 \le N, M \le 2000). Each of the next MM lines describes one allowed turn: a letter, L (left) or P (right), giving the direction, then a space, then a natural number xx (0<x<N0 < x < N) giving how many steps it turns. All MM turns are pairwise different.

The next line contains a natural number TT (1≤T≤101 \le T \le 10), the number of pairs (R,k)(R, k) to check. Each of the following TT lines contains two positive integers RR (1≤R≤1091 \le R \le 10^9) and kk (1≤k≤N1 \le k \le N).

Output

For each pair (R,k)(R, k), print on its own line a single non-negative integer: the number of different ordered sequences of RR turns that open the safe (that is, leave kk at the top), taken modulo 10000331000033.

Examples3

  1. Example 1

    Input
    1
    3 3
    L 1
    P 1
    P 2
    3
    1 3
    1 2
    2 1
    
    Expected output
    1
    2
    4
    
  2. Example 2

    Input
    1
    2 1
    P 1
    3
    1 1
    1 2
    2 1
    
    Expected output
    0
    1
    1
    
  3. Example 3

    Input
    1
    4 3
    P 1
    L 1
    P 2
    6
    1 1
    1 2
    1 3
    1 4
    3 1
    3 3
    
    Expected output
    0
    1
    1
    1
    6
    7