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
题解
知道了错排这题就pj难度了.
错排公式D[n]=(n-1)*(D[n-1]+D[n-2]) D[1]=0 D[2]=1
预处理一下组合再预处理一下错排数
答案就是
Cmn∗D[n−m] C n m ∗ D [ n − m ]
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
const LL mod=1e9+7;
LL pre[1110000],D[1110000];
LL pow_mod(LL a,int b)
{
LL ret=1;
while(b)
{
if(b&1)ret=ret*a%mod;
a=a*a%mod;b>>=1;
}
return ret;
}
int n,m,T;
int main()
{
scanf("%d",&T);
pre[1]=pre[0]=1;for(int i=2;i<=1000000;i++)pre[i]=pre[i-1]*i%mod;
D[0]=1;D[1]=0;D[2]=1;
for(int i=3;i<=1000000;i++)D[i]=(i-1)*(D[i-1]+D[i-2])%mod;
while(T--)
{
scanf("%d%d",&n,&m);
LL p=pre[n]*pow_mod(pre[m],mod-2)%mod*pow_mod(pre[n-m],mod-2)%mod;
LL q=D[n-m];
printf("%lld\n",p*q%mod);
}
return 0;
}