Wand FZU - 2282 错排公式
Wand FZU - 2282
错拍公式:有十本书放在书架上,问重新摆放之后没有书在自己原来的位置上的摆放方式有多少种?
设n本书的错拍方式为D[n],那么把第n本书放在第k个位置,k有n-1种取值。对于第k个元素,要么放在第n个位置,此时剩下的就是n-2个元素的错拍 D[n-2],如果第k个元素不放在第n个位置,那么可以想想n对应的就是k,要求k不能放在n处,就是n-1个元素的错拍D[n-1]。于是D[n] = (n-1)*(D[n- 1]+D[n-2])。
N wizards are attending a meeting. Everyone has his own magic wand. N magic wands was put in a line, numbered from 1 to n(Wand_i owned by wizard_i). After the meeting, n wizards will take a wand one by one in the order of 1 to n. A boring wizard decided to reorder the wands. He is wondering how many ways to reorder the wands so that at least k wizards can get his own wand.
For example, n=3. Initially, the wands are w1 w2 w3. After reordering, the wands become w2 w1 w3. So, wizard 1 will take w2, wizard 2 will take w1, wizard 3 will take w3, only wizard 3 get his own wand.
Input
First line contains an integer T (1 ≤ T ≤ 10), represents there are T test cases.
For each test case: Two number n and k.
1<=n <=10000.1<=k<=100. k<=n.
Output
For each test case, output the answer mod 1000000007(10^9 + 7).
Sample Input
2 1 1 3 1
Sample Output
1 4
题意:有n个巫师,每个巫师有一个魔法棒,现在要把魔法棒打乱顺序,巫师按照顺序领取魔法棒,问至少要有k个巫师领到自己的魔法棒的排列当时有多
少种?
题解:如果我们遍历有k、k+1、k+2...n个巫师领到自己的魔法棒,一定可以出来结果。
x个巫师领到自己的魔法棒,公式为 C(n,x)*D[n-x],预处理的话,需要把所有的C(n,x)都预处理出来,但是由于只有10组测试样例,所以不需要预处理,
于是对于每一组测试样例,我们需要把C(n , 1~n)都求出来,且O(n)的时间求出来D[n-x],这样的话,应该也不会超时,但是可以直接枚举不可以的减去就
行了