Luogu P4071 [SDOI2016]排列计数

题目描述:传送门

题解:

这题是一道排列组合问题。
我们注意到有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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值