Watson is curious about parallel computing. He wants to sort a permutation of the integers 1 through N by breaking it into chunks, sorting each chunk on its own, and concatenating the sorted chunks.
For a permutation p1,p2,…,pN, a chunk is a contiguous subarray: the elements pi,pi+1,…,pj for indexes i and j with 1≤i≤j≤N.
Watson partitions his permutation into an ordered list of one or more chunks without changing the order of the elements, so that every element belongs to exactly one chunk and every element of a chunk is smaller than every element of any later chunk. For the permutation [2, 1, 3, 5, 4] there are exactly four legal partitions:
[[2, 1, 3], [5, 4]]
[[2, 1], [3, 5, 4]]
[[2, 1], [3], [5, 4]]
[[2, 1, 3, 5, 4]]
Watson is happiest when the number of chunks is as large as possible. Write f(p) for the maximum number of chunks of a permutation p. For the permutation above, f(p)=3.
Take every permutation p of the numbers 1 through N and add up f(p)2. The sum can be large, so report it modulo M.