#P16583. [GKS 2016 #B] Sherlock and Permutation Sorting

[GKS 2016 #B] Sherlock and Permutation Sorting

题目描述

Sherlock and Watson have already been introduced to sorting in their computer programming course. Now, Watson has always been curious about parallel computing and wants to sort a permutation of the integers 11 through NN by breaking it into chunks, sorting the chunks individually, and then concatenating them.

For a permutation p1,p2,,pNp_1, p_2, \dots, p_N, a chunk is a contiguous subarray of the permutation: i.e., a sequence of elements pi,pi+1,,pjp_i, p_{i+1}, \dots, p_j, for the elements at indexes ii and jj such that 1ijN1 \leq i \leq j \leq N.

Watson wants to partition his permutation into an ordered list of one or more chunks, without changing the order that the elements are in, in such a way that each element of the permutation is in exactly one chunk, and all elements in a chunk are smaller than all elements in any later chunk. For example, for the permutation [2,1,3,5,4][2, 1, 3, 5, 4], these are the only four legal ways for Watson to break it into chunks: [[2,1,3],[5,4]][[2, 1, 3], [5, 4]] or [[2,1],[3,5,4]][[2, 1], [3, 5, 4]] or [[2,1],[3],[5,4]][[2, 1], [3], [5, 4]] or [[2,1,3,5,4]][[2, 1, 3, 5, 4]]. Watson is happiest when there are as many chunks as possible; we denote the maximum number of chunks for a permutation pp as f(p)f(p). In this example, the maximum number of chunks is 33.

Watson wants to consider all permutations pp of the numbers 11 through NN, and find the sum of squares of f(p)f(p). Watson knows Sherlock might come in handy and comes to him for help, but Sherlock is as clueless as Watson and asks you for help. As the sum of squares can be large, please find it modulo MM.

输入格式

The first line of the input gives the number of test cases, TT. TT test cases follow. Each test case consists of one line with two integers NN and MM.

输出格式

For each test case, output one line containing Case #x: y, where xx is the test case number (starting from 1) and yy is the sum of squares of f(p)f(p) for all permutations pp of size NN, modulo MM.

3
1 2
2 4
3 7
Case #1: 1
Case #2: 1
Case #3: 6

提示

In Case 1, there is only one permutation. f([1])×f([1])mod2=1f([1]) \times f([1]) \bmod 2 = 1.

In Case 2, there are two permutations. f([1,2])=2f([1, 2]) = 2. f([2,1])=1f([2, 1]) = 1. (22+12)mod4=1(2^2 + 1^2) \bmod 4 = 1.

In Case 3, there are six permutations. f([1,2,3])=3f([1, 2, 3]) = 3. f([1,3,2])=2f([1, 3, 2]) = 2. f([2,1,3])=2f([2, 1, 3]) = 2. f([2,3,1])=1f([2, 3, 1]) = 1. f([3,1,2])=1f([3, 1, 2]) = 1. f([3,2,1])=1f([3, 2, 1]) = 1. (32+22+22+12+12+12)mod7=6(3^2 + 2^2 + 2^2 + 1^2 + 1^2 + 1^2) \bmod 7 = 6.

Limits

1M1091 \le M \le 10^9.

Small dataset (Test set 1 - Visible)

1T1001 \le T \le 100.

1N1001 \le N \le 100.

Large dataset (Test set 2 - Hidden)

1T201 \le T \le 20.

1N50001 \le N \le 5000.