Between Strings
Between Strings
Between Strings
Today, in an algorithms course, Hanh learns lexicographical order.
The professor gives Hanh a counting task: Given two strings a and b and an integer l, count
the number of strings c of length l such that c is greater than a and less than b, in terms of
lexicographical order.
This task is quite a simple one for Hanh. He manages to write the below function in a matter
of second: countBetween(a, b, l, p). This function works as below:
• It has four parameters: a and b are two strings of lowercase English letters, l and p are
two positive integers.
• It correctly counts the number of strings c containing exactly l lowercase English letters,
satisfying a < c < b in terms of lexicographical order.
• It returns a non-negative integer which is the remainder after dividing the number of such
strings c by p.
To make thing more interesting and challenging for Hanh, his professor now asks him to
proceed multiple queries of counting strings between. In order to solve this harder problem,
Hanh writes the following pseudo code:
sum = 0
for each integer l in d:
sum += countBetween(a, b, l, p)
return res
• Two strings s and w of the same length, s contains lowercase English characters only,
w contains characters A and B only.
In the above pseudo code, length(s) denotes the number of characters of string s, while
s[i] denotes the i-th character of string s. Characters are numbered starting from 0.
Sadly, Hanh realizes that his code may run too slow with some of the professor’s test data.
Hence, he asks you to write a program to efficiently calculate the returning value of the above
function, given the values of all its parameters.
As a reminder, a string X = x0 x1 x2 . . . xm is considered lexicographically less than a string
Y = y0 y1 y2 . . . yn iff either of the below conditions hold:
• There exists an index i such that i min(m, n), xi < yi and xj = yj for every 0 j < i.
Input
• The first line contains three integers q, n and p (1 q 2 · 106 , 1 n 7 · 104 , 1
p 109 ) — the length of parameters s and w, the number of elements of parameter d
and the value of parameter p, respectively.
• The third line contains a string of exactly q lowercase English characters — the parameter
s.
• The forth line contains a string of exactly q characters A and B — the parameter w.
Output
Print a single integer — the returned value of the above function solve.