Reading
Time limit5sMemory limit128 MB
Count non-empty lowercase words whose total adjacent-letter difference is at most N, modulo 1e9+7.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Combinatorics
- Solved
- No attempts yet
Problem
A curious fact about the human brain is that, when we read, it mostly looks at the first and last letter of each word and fills in the rest — so a sentence whose inner letters are shuffled can still be read almost effortlessly.
Elly noticed that some shuffles read better than others: the letters l and i, or a and o, look much more alike than, say, x and m. She rates the difference between two letters on a scale from to — similar letters get a low value, very different letters a high one. Two equal letters always have difference .
The value of a word is the sum of the differences between every pair of adjacent letters. For example, if the difference between e and l is , between l and y is , and between i and l is , then the word elly has value (recall that the equal pair l-l contributes ). With those same differences the word lily has value , and a single letter such as i has value .
A longer word is not always worth more than a shorter one: lilii has value only , while elle has value . Still, every extra letter adds at least to a word's value.
Elly wants to design a language that stays easy to read even with many misplaced letters, so she will include every non-empty word whose value is at most . Help her by counting how many such words there are.
Input
The first line contains two integers and — the largest allowed word value () and the number of letter pairs for which a difference is defined.
Each of the next lines contains L1 L2 F, meaning the difference between the lowercase letters and is (). The difference is symmetric, so it is the same from to and from to . Every pair not listed has difference .
Output
Print a single integer — the number of non-empty words made of lowercase English letters whose value is at most . Because this count can be enormous, print it modulo .
Notes
As a bit of trivia, elleonora, entwine, and aaaaaaaaaaaaaaaaaaaaa are among the words that satisfy the condition.