#P1097H. Mateusz and an Infinite Sequence
Mateusz and an Infinite Sequence
Description
A Thue-Morse-Radecki-Mateusz sequence (Thorse-Radewoosh sequence in short) is an infinite sequence constructed from a finite sequence of length and an integer , obtained in the following sequence of steps:
- In the beginning, we define the one-element sequence .
- In the -th step, , we define the sequence to be the concatenation of the copies of . However, each of them is altered slightly — in the -th of them (), each element is changed to .
For instance, if we pick and :
- ,
- ,
- ,
- , and so on.
As you can see, as long as the first element of is , each consecutive step produces a sequence whose prefix is the sequence generated in the previous step. Therefore, we can define the infinite Thorse-Radewoosh sequence as the sequence obtained by applying the step above indefinitely. For the parameters above, .
Mateusz picked a sequence and an integer , and used them to obtain a Thorse-Radewoosh sequence . He then picked two integers , , and wrote down a subsequence of this sequence .
Note that we use the -based indexing both for and .
Mateusz has his favorite sequence with length , and would like to see how large it is compared to . Let's say that majorizes sequence of length (let's denote it as ) if and only if for all , we have .
He now asks himself how many integers in the range there are such that . As both sequences were huge, answering the question using only his pen and paper turned out to be too time-consuming. Can you help him automate his research?
The first line contains two integers and (, ) — the length of the sequence and an integer used to perform the modular operations. The second line contains integers (). It's guaranteed that the first element of the sequence is equal to zero.
The third line contains one integer () — the length of the sequence . The fourth line contains integers (). The fifth line contains two integers and (, ).
Print a single integer — the answer to the problem.
Input
The first line contains two integers and (, ) — the length of the sequence and an integer used to perform the modular operations. The second line contains integers (). It's guaranteed that the first element of the sequence is equal to zero.
The third line contains one integer () — the length of the sequence . The fourth line contains integers (). The fifth line contains two integers and (, ).
Output
Print a single integer — the answer to the problem.
Note
Thorse-Radewoosh sequence in the first example is the standard Thue-Morse sequence, so the sequence is as follows: . Here are the places where the sequence majorizes :
