4517: [Sdoi2016]排列计数
Time Limit: 60 Sec Memory Limit: 128 MBSubmit: 1259 Solved: 766
[ Submit][ Status][ Discuss]
Description
求有多少种长度为 n 的序列 A,满足以下条件:
1 ~ n 这 n 个数在序列中各出现了一次
若第 i 个数 A[i] 的值为 i,则称 i 是稳定的。序列恰好有 m 个数是稳定的
满足条件的序列可能很多,序列数对 10^9+7 取模。
Input
第一行一个数 T,表示有 T 组数据。
接下来 T 行,每行两个整数 n、m。
T=500000,n≤1000000,m≤1000000
Output
输出 T 行,每行一个数,表示求出的序列数
Sample Input
5
1 0
1 1
5 2
100 50
10000 5000
Sample Output
0
1
20
578028887
60695423
会错排这题一看就发现了
n个中有m个数稳定情况是C(n, m),直接阶乘打标+逆元
然后剩下n-m个数错排,公式是F[n] = (n-1)*(F[n-1]+F[n-2])
最后相乘
错排问题blog(我的):
http://blog.csdn.net/jaihk662/article/details/52251034
#include<stdio.h>
#define LL long long
#define mod 1000000007
LL jc[1000005] = {1,1,2}, F[1000005] = {1,0,1};
LL Pow(LL a, LL b)
{
LL ans;
ans = 1;
while(b)
{
if(b%2==1)
ans = (ans*a)%mod;
a = (a*a)%mod;
b /= 2;
}
return ans;
}
LL C(LL n, LL m)
{
LL ans;
if(n<m)
return 0;
ans = (jc[n]*Pow((jc[m]*jc[n-m])%mod, mod-2)%mod)%mod;
return ans;
}
int main(void)
{
LL T, n, m, i;
for(i=3;i<=1000000;i++)
{
F[i] = (F[i-1]+F[i-2])*(i-1)%mod;
jc[i] = jc[i-1]*i%mod;
}
scanf("%lld", &T);
while(T--)
{
scanf("%lld%lld", &n, &m);
printf("%lld\n", C(n, m)*F[n-m]%mod);
}
return 0;
}