#P6841. [BalkanOI 2009] Reading
[BalkanOI 2009] Reading
Background
Problem Description
There is an interesting fact about the human brain: when reading, it mainly looks at the first and last letter of each word, and it does not necessarily need the letters inside to be in the correct order to recognize the word. Therefore, even if a sentence has almost no words spelled correctly, it may still be understood correctly. (In the original text, some words in this paragraph have their letters shuffled, but the translator believes this would affect readability, so the order of letters in the translated text is kept unchanged.)
Elly has noticed that shuffling certain letters can give even better results. For example, the letters l and i, a and o, x and m look very similar. So she defines a value for a pair of letters, from to . Similar letters have a smaller value, and very different letters have a larger value. The value for equal letters is . In this way, each word can be assigned a value—the sum of the values of all adjacent letter pairs.
Imagine she defines the value between e and l as , between l and y as , and between i and l as . Then the value of the word elly is (remember that the distance between equal adjacent letters is ). The value of the word lily is , while the value of i is .
Long words do not necessarily have a larger value than short words—for example, lilii (the plural form of lily in Bulgarian) has value only , but elle (meaning she in French) has value . However, each time you add one letter, the value of the word increases by at least .
Ellenora wants to design a language that is easy to read even with lots of scrambled letters. Find the number of all non-empty words whose value is not greater than .
Input Format
Read from standard input.
The first line contains two integers and , representing the maximum allowed word value () and the number of given letter pairs. Elly has defined a value for these pairs. For all letter pairs not mentioned, the distance is . Each of the next lines contains a triple , meaning the distance between the letters is . The distance from to is the same as from to , i.e. the distance is unordered.
Output Format
Write to standard output.
Output one integer: the number of words consisting of lowercase English letters whose value is not greater than . Since this number can be very large, output it modulo .
20 10
e l 3
e o 1
o n 2
o r 4
r a 4
i n 5
e n 2
n t 3
t w 3
w i 5
470059518
Hint
Constraints
For of the testdata, .
For all testdata, , and each unordered pair of letters appears at most once.
Sample Explanation
Some valid words are: elleonora, entwine, aaaaaaaaaaaaaaaaaaaaa.
Translated by ChatGPT 5