P4071 [SDOI2016]排列计数

P4071 [SDOI2016]排列计数
C(n,m)*f[n-m],f函数为错排数,特判n==m的时候,ans=1

#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cstring>
#define inf 2147483647
#define N 1000010
#define mod 1000000007
#define p(a) putchar(a)
#define For(i,a,b) for(long long i=a;i<=b;++i)
//by war
//2019.8.7
using namespace std;
long long T,n,m,f[N],a[N],x,y,ans;
void in(long long &x){
    long long y=1;char c=getchar();x=0;
    while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();}
    while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();}
    x*=y;
}
void o(long long x){
    if(x<0){p('-');x=-x;}
    if(x>9)o(x/10);
    p(x%10+'0');
}

void exgcd(long long a,long long b,long long &x,long long &y){
    if(!b){
        x=1;y=0;
        return;
    }
    exgcd(b,a%b,y,x);
    y-=a/b*x;
}

signed main(){
    in(T);
    f[2]=1;a[0]=1;
    For(i,3,1000000)
        f[i]=(i-1)*(f[i-1]+f[i-2])%mod;
    For(i,1,1000000)
        a[i]=a[i-1]*i%mod;
    while(T--){
        in(n);in(m);
        ans=a[n];
        exgcd(a[m],mod,x,y);
        x=(x%mod+mod)%mod;
        ans=ans*x%mod;
        exgcd(a[n-m],mod,x,y);
        x=(x%mod+mod)%mod;
        ans=ans*x%mod;
        ans=ans*f[n-m]%mod;
        if(n==m)
            ans=1;
        o(ans);p('\n');
    }
    return 0;
}

 

posted @ 2019-08-07 21:06  WeiAR  阅读(159)  评论(0编辑  收藏  举报