题目描述:传送门
题解:
这题是一道排列组合问题。
我们注意到有m个数是对应的,就可以用C(n,m)来计算。因为要mod,再用一下逆元就好了。
还有n-m个位置是每一个都是错位的,这就是经典的错排公式:D(n)=(n-1)*(D(n-1)+D(n-2))。预处理一下就好了。
注意D(0)=1!!!
代码如下:
#include<cstdio>
#include<string>
using namespace std;
const int maxn=1000005,tt=1000000007;
int T,n,m;
long long calc[maxn],pow[maxn];
inline int read(){
int x=0; char ch=getchar();
while (ch<'0'||ch>'9') ch=getchar();
while (ch>='0'&&ch<='9') x=x*10+ch-48,ch=getchar();
return x;
}
long long qsm(long long x,int y){
long long ret=1,w=x;
while (y) {
if (y%2==1) ret=(ret*w)%tt;
w=(w*w)%tt; y/=2;
}
return ret;
}
long long c(int x,int y,int z) {return 1ll*(pow[x]*qsm(pow[y]*pow[z]%tt,tt-2))%tt;}
int main(){
T=read(); calc[1]=0ll; calc[2]=1ll; calc[0]=1ll; pow[0]=1ll;
for (int i=3;i<=1000000;i++) calc[i]=(i-1)*(calc[i-1]+calc[i-2])%tt;
for (int i=1;i<=1000000;i++) pow[i]=pow[i-1]*i%tt;
while (T--) {
n=read(),m=read();
printf("%lld\n",c(n,m,n-m)*calc[n-m]%tt);
}
return 0;
}