Balanced Garden in a Row

Time limit2sMemory limit128 MB

Summary
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 NN 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 22.

Thus a garden can be written as a single string of L and P. For example, when N=5N = 5 there are exactly 1414 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 11, where L comes before P. For example, when N=5N = 5 the 1212th string is PLPPL.

Given a balanced garden string of length NN, find its rank — its position in lexicographic order among all balanced garden strings of the same length — and print that rank modulo the integer MM.

MM is provided only to make the computation easier and has no other meaning.

Input

The first line contains the number of plants NN. (1≤N≤1061 \le N \le 10^6)

The second line contains an integer MM. (7≤M≤1077 \le M \le 10^7)

The third line contains a balanced garden string of length NN, made up of L (lotus) and P (papyrus).

Output

Print, on a single line, the lexicographic rank of the given garden string modulo MM. This value is an integer in the range from 00 to M−1M - 1.

Hint

In the first example, PLPPL is the 1212th balanced garden string of length N=5N = 5 in lexicographic order. Therefore the answer is 12 mod 7=512 \bmod 7 = 5.

Examples2

  1. Example 1

    Input
    5
    7
    PLPPL
    
    Expected output
    5
    
  2. Example 2

    Input
    12
    10000
    LPLLPLPPLPLL
    
    Expected output
    39