Since the total error is at most , each term satisfies . Because and , all possible pitches lie between and . This range contains integers.
Let be the number of sequences consisting of the first terms whose total error is exactly and whose last pitch is . Store states with and .
The first pitch is fixed at , so its error is . If , initialize
All other states are . If , no valid sequence exists, so we can immediately print .
Now suppose and we choose as the last pitch. The error on this term is , so the total error on the first terms must be . The previous pitch must satisfy . Thus, for ,
States with have value .
Process in order. For each error and last pitch , compute the sum by directly iterating over the values of in the interval above. Perform all additions modulo .
The final answer is
We must sum all states whose error is at most , rather than counting only those whose error is exactly .
There are states, and each state checks at most previous pitches. Therefore, the time complexity is
These factors correspond to number of terms × pitch range × total error range × range of differences between adjacent pitches. Under the given constraints, we can compute these transitions directly.
Since each step uses only the immediately preceding step, we only need to store two layers of the array. The space complexity is . Map pitch to array index .
Proof
The first term is uniquely fixed at , and its error is . Thus, setting when counts the valid sequence of length exactly once. If , later terms cannot decrease the total error, so the answer is .
Solution written by GPT6
Assume that is correct. Removing the last term from a valid sequence whose last pitch is and whose total error is leaves a previous sequence with error and last pitch satisfying .
Conversely, appending to any such previous sequence satisfies the restriction on adjacent pitches and makes the total error exactly . These two operations are inverses, so the transition counts every valid sequence exactly once. Summing all final states with gives the required answer.