P4071 [SDOI2016] 排列计数

LLink

显然的,答案就是\(C_n^m*D_{n-m}\)

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<ctime>
#include<bitset>
using namespace std;
int t;
long long n,m;
const long long mod=1e9+7;
long long f[1000005];
long long inv[1000005];
long long d[1000005];
long long qm(long long a,long long b){
	long long res=1;
	while(b>0){
		if(b&1) res=(a*res)%mod;
		a*=a;
		a%=mod;
		b>>=1;
	}
	return res;
}
int main(){
	scanf("%d",&t);
	f[0]=1;
	inv[0]=1;
	for(long long i=1;i<=1000002;++i){
		f[i]=(f[i-1]*i)%mod;
		inv[i]=qm(f[i],mod-2);
	}
	d[1]=0;
	d[2]=1;
	d[3]=2;
	for(long long i=4;i<=1000002;++i){
		d[i]=(i-1)*(d[i-1]+d[i-2])%mod;
	}
	while(t--){
		scanf("%lld%lld",&n,&m);
		if(m==0) {
			printf("%lld\n",(d[n]+mod)%mod);
		}else if(m!=n){
			printf("%lld\n",(f[n]*inv[m]%mod*inv[n-m]%mod*d[n-m]%mod+mod)%mod);
		}else{
			cout<<1<<endl;
		}
	}
	return 0;
}
posted @ 2023-09-17 16:50  Simex  阅读(3)  评论(0编辑  收藏  举报