Sherlock and Permutation Sorting (Large)
Time limit10sMemory limit512 MB
For each N and modulus M, sum f(p)^2 over all permutations of 1..N, where f(p) is the maximum number of blocks that can be sorted independently; output the sum mod M.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Combinatorics, Prefix sum, Math
- Solved
- No attempts yet
Problem
Sherlock and Watson learned sorting in their programming course. Watson is curious about parallel computing, so he wants to sort a permutation of the integers through by splitting it into chunks, sorting each chunk on its own, and then concatenating them.
For a permutation , a chunk is a contiguous subarray: the elements for indices and with .
Watson partitions the permutation into an ordered list of one or more chunks without changing the order of the elements. Every element belongs to exactly one chunk, and every element of a chunk is smaller than every element of every later chunk. For example, for the permutation these are the only four legal partitions.
Watson is happiest when there are as many chunks as possible. Write for the maximum number of chunks of a permutation . In the example above that maximum is .
Compute the sum of over all permutations of the numbers through . The sum can be large, so print it modulo .
Input
The first line contains the number of test cases, . test cases follow. Each test case is one line with two integers and separated by a space.
Output
For each test case, print one line in the form Case #x: y, where is the test case number starting from and is the sum of over all permutations of size , modulo .
Constraints
Notes
For the only permutation is and , so the sum of squares is .
For there are two permutations. and , so the sum of squares is .
For there are six permutations. , , , , , , so the sum of squares is .
If is , the remainder is always .