Anna wants to open a marvelous restaurant, "Candy Mountain", serving only candy kabobs: sticks on which one puts various pieces of food, to be eaten from the tip to the base.
Like other kabob enthusiasts, when Anna eats a pattern of consecutive types of food in a kabob, she expects to eat another pattern later in the kabob. For instance, once she eats a piece of apple immediately followed by a piece of banana, she expects to have a leaf of mint immediately followed by chocolate in the remaining part of the kabob. She is happy if she finds this mint-chocolate pattern anywhere in the remaining kabob pieces.
Here is a kabob that Anna likes:
Apple-Banana-Watermelon-Plum-Watermelon-Plum-Watermelon-Mint-Chocolate
or, graphically:
Anna has written down her perfect set of kabob patterns for the new restaurant, but she worries
that these rules would give too many potential kabob types. This set of patterns is written down as a
ruleset, where each rule is of the form " implies afterwards", where and are non-empty sequences
of characters, representing food pieces. A rule of the form b > e
with and
means that, if the pattern is encountered in the kabob, then the kabob should also contain at some
point after. Each must immediately follow to trigger the rule and similarly each must
immediately follow to satisfy it, but and do not need to be consecutive. No food piece can
appear more than once in a rule (i.e., there is no , such that and no with or )
but a food piece can appear in several rules.
Note that if there are several occurrences of the word in a kabob, they all need to be followed by an . This can be a single , as long as this appears after all the .
In a ruleset, rules are separated by |
and are of the form u > v
meaning that each pattern implies
a pattern afterwards. and are words composed of alphanumeric characters and no character
can appear twice in a rule. For instance, the ruleset AB>X|R>A|T>B
describes three rules:
- for each
AB
there must be anX
afterwards; - for each
R
there must be anA
afterwards; and - for each
T
there must be aB
afterwards.
Using this ruleset, the kabobs SBSB
, REA
, ABX
, BA
, ABXBA
, RRA
, TBTB
, and RTABX
are valid; but RAT
,
TAB
, and ABXAB
are not.
Anna asks you how many kabobs of a given size are compatible with her ruleset.
Input Specification
- The first line contains an integer , the size of all kabobs, followed by a space, and a non-empty
string of alphanumeric characters (
A
toZ
,a
toz
, and0
to9
), representing the elements that can be used in a kabob (no characters appear twice in ). - The second line contains a non-empty string , which contains no spaces and represents a ruleset as described above. The patterns in are composed of characters from only.
Constraints
The input is such that and .
Output Specification
One integer: the number of kabobs of length satisfying all the rules in , modulo .
Sample Input
4 ABC
A>B|B>C|CB>A
Sample Output
9
Comments