Balanced Garden in a Row
Time limit2sMemory limit128 MB
Count balanced binary strings of length N whose every substring has at most two more L than P, and find the lexicographic rank of a given string modulo M.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Combinatorics, Math, String matching
- Solved
- No attempts yet
Problem
Ramesses II has returned victorious from battle and, to celebrate, decides to build a magnificent garden. Along the long road that runs from the palace at Lubrr to the temple at Karnak, he will plant a single row of plants. Only two kinds of plants are available: the lotus (L) and the papyrus (P), because they are the symbols of Lower and Upper Egypt respectively.
He plants plants in this way, and the arrangement of the two kinds must be balanced. Balanced means that for every contiguous segment of the garden, the difference between the number of lotuses and the number of papyri inside it never exceeds .
Thus a garden can be written as a single string of L and P. For example, when there are exactly balanced gardens:
LLPLP, LLPPL, LPLLP, LPLPL, LPLPP, LPPLL, LPPLP, PLLPL, PLLPP, PLPLL, PLPLP, PLPPL, PPLLP, PPLPL
If we list all balanced garden strings of the same length in ascending (lexicographic) order, we can number them starting from , where L comes before P. For example, when the th string is PLPPL.
Given a balanced garden string of length , find its rank — its position in lexicographic order among all balanced garden strings of the same length — and print that rank modulo the integer .
is provided only to make the computation easier and has no other meaning.
Input
The first line contains the number of plants . ()
The second line contains an integer . ()
The third line contains a balanced garden string of length , made up of L (lotus) and P (papyrus).
Output
Print, on a single line, the lexicographic rank of the given garden string modulo . This value is an integer in the range from to .
Hint
In the first example, PLPPL is the th balanced garden string of length in lexicographic order. Therefore the answer is .