luogu#P4685. [IOI 2008] Linear Garden

[IOI 2008] Linear Garden

Problem Description

Ramesses II has just returned victorious. To commemorate this victory, he decided to build a magnificent garden. The plants in this garden are arranged in a single line, stretching from his palace in Luxor all the way to the Karnak Temple. The only plants used are lotus and papyrus, because they represent Upper Egypt and Lower Egypt, respectively.

The garden must contain NN plants and must be balanced. That is, for any segment chosen within the garden, the difference between the number of lotus and the number of papyrus in that segment must not exceed 22.

The garden can be represented as a string consisting of the letters L (lotus) and P (papyrus). For example, when N=5N=5, there are 1414 possible balanced gardens. In lexicographical order, they are: LLPLP, LLPPL, LPLLP, LPLPL, LPLPP, LPPLL, LPPLP, PLLPL, PLLPP, PLPLL, PLPLP, PLPPL, PPLLP, and PPLPL.

All possible balanced gardens of a given length can be sorted in lexicographical order and numbered starting from 11. For example, when N=5N=5, garden number 1212 is PLPPL.

Write a program that, given the number of plants NN and a string representing a balanced garden, computes the garden’s index modulo MM, where MM is a given integer. Note that in solving the problem, the value MM has no purpose other than simplifying the computation.

Input Format

The first line contains an integer NN, the number of plants in the garden. The second line contains an integer MM. The third line contains a string of length NN consisting of characters L or P, representing a balanced garden.

Output Format

Your program should output to standard output a single integer between 00 and M1M-1 (inclusive), on one line, representing the garden’s index modulo MM.

5
7
PLPPL
5
12
10000
LPLLPLPPLPLL
39

Hint

There are test points worth 40 points where NN does not exceed 4040.

For all test points, 1N1,000,0001\le N\le 1,000,000 and 7M10,000,0007\le M \le 10,000,000.

Sample Explanation

In the first sample, the actual index is 12. Therefore, the output is 1212 modulo 77, which is 55.

Translated by ChatGPT 5