Sherlock and Permutation Sorting (Small)
Time limit5sMemory limit512 MB
For every permutation of 1..N, find the maximum number of order-preserving chunks with all earlier-chunk values smaller than later ones, then sum f(p)^2 modulo M.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Combinatorics, Math, Prefix sum
- Solved
- No attempts yet
Problem
Watson is curious about parallel computing. He wants to sort a permutation of the integers 1 through by breaking it into chunks, sorting each chunk on its own, and concatenating the sorted chunks.
For a permutation , a chunk is a contiguous subarray: the elements for indexes and with .
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 for the maximum number of chunks of a permutation . For the permutation above, .
Take every permutation of the numbers 1 through and add up . The sum can be large, so report it modulo .
Input
The first line contains the number of test cases, . Each of the next lines contains two integers and .
Output
For each test case, print one line in the form Case #x: y, where is the test case number starting from 1 and is the sum of over all permutations of size , modulo .
Constraints
is not always prime, and is allowed.
Explanation
For there is a single permutation and , so the sum of squares is 1.
For there are two permutations, and , so the sum of squares is .
For the six permutations give , , , , and , so the sum of squares is .