错排公式:
d(n)=(n-1)*(d(n-1)+d(n-2));
ans=C(n,m)*d(n-m);
其中需要预处理阶乘和逆元。
逆元线性递推如下:inv[i]=(mod-mod/i)*inv[mod%i]%mod;
/*
Staggered Formula:
d(n)=(n-1)*(d(n-1)+d(n-2));
ans=C(n,m)*d(n-m);
inv[i]=(mod-mod/i)*inv[mod%i]%mod;
*/
#include
using namespace std;
const int maxn=1e6+2,mod=1e9+7;
typedef long long ll;
ll fac[maxn],inv[maxn],d[maxn];
inline int read() {
int x=0,f=1;char c=getchar();
while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();}
while (c>='0'&&c<='9') x=x*10+c-'0',c=getchar();
return x*f;
}
int main() {
// freopen("bzoj 4517.in","r",stdin);
fac[0]=fac[1]=inv[0]=1,inv[1]=1,d[0]=1,d[1]=0;
for (register int i=2;i1]*i%mod,
inv[i]=(mod-mod/i)*inv[mod%i]%mod,
d[i]=(i-1)*(d[i-1]+d[i-2])%mod;
}
for (register int i=2;i*inv[i-1]%mod;
int kase=read();
for (register int r=1;r<=kase;++r) {
int n=read(),m=read();
printf("%lld\n",fac[n]*inv[n-m]%mod*inv[m]%mod*d[n-m]%mod);
}
return 0;
}