淘先锋技术网

首页 1 2 3 4 5 6 7

http://www.lydsy.com/JudgeOnline/problem.php?id=4517

 

组合数+错排公式

 

#include<cstdio>
#include<iostream>

using namespace std;

#define N 1000001

const int mod=1e9+7;

long long fac[N],inv[N],f[N];

void read(int &x)
{
    x=0; char c=getchar();
    while(!isdigit(c)) c=getchar();
    while(isdigit(c)) { x=x*10+c-'0'; c=getchar(); }
}

int Pow(long long a,int b)
{
    long long res=1;
    for(;b;a=a*a%mod,b>>=1)
        if(b&1) res=res*a%mod;
    return res;
}

int main()
{
    freopen("permutation.in","r",stdin);
    freopen("permutation.out","w",stdout);
    fac[0]=fac[1]=1;
    for(int i=1;i<N;++i) fac[i]=fac[i-1]*i%mod;
    inv[0]=inv[1]=1;
    for(int i=1;i<N;++i) inv[i]=Pow(fac[i],mod-2); 
    f[0]=f[2]=1;
    for(int i=3;i<N;++i) f[i]=(i-1)*(f[i-1]+f[i-2])%mod;
    int T,n,m;
    read(T);
    while(T--)
    {
        read(n); read(m);
        printf("%d\n",int(f[n-m]*fac[n]%mod*inv[m]%mod*inv[n-m]%mod));
    }
    fclose(stdin); fclose(stdout);    
    return 0;
}

 

转载于:https://www.cnblogs.com/TheRoadToTheGold/p/8573333.html