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
题解
错排裸题
因为原序列中有m个数在其下标的位置上,所以有n-m个数是错位的。
错排递推公式
然后再乘剩下的数的组合就可以辣!!!
My Code
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<cstring>
#define wn 1000000007
using namespace std;
typedef long long ll;
ll f[2001412],fac[2001412];
ll n,m,T;
ll inv(ll x) {
ll y=wn-2,ans=1;
while (y) {
if (y&1) ans=ans*x%wn;
x=x*x%wn;
y>>=1;
}
return ans;
}
ll C(ll n,ll m){
ll res=fac[n];
res=(res*inv(fac[n-m]))%wn;
res=(res*inv(fac[m]))%wn;
return res;
}
int main() {
scanf("%lld",&T);
f[0]=1,fac[0]=1;
f[1]=0,fac[1]=1;
for(ll i=2;i<=1000001;i++){
f[i]=((f[i-1]+f[i-2])%wn*(i-1))%wn;
fac[i]=fac[i-1]*i%wn;
}
while(T--){
scanf("%lld%lld",&n,&m);
printf("%lld\n",(f[n-m]*C(n,m))%wn);
}
}