算法基础之组合数 II
-
核心思想:快速幂求逆元
- 前置:C^b^~a~ = a! /(b! * (a-b)!)
- 即 fac[a] * infac[b] * infac[a-b];
- 前置:C^b^~a~ = a! /(b! * (a-b)!)
cpp
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int MOD = 1e9+7,N = 1e5+10;
typedef long long LL;
long long fac[N],infac[N];
int n;
int qmi(int a,int b,int k) //快速幂求逆元
{
int res = 1;
while(b)
{
if(b&1) res = (LL)res*a%k;
b>>=1;
a = (LL)a*a%k;
}
return res;
}
int main()
{
fac[0] = infac[0] = 1;
for(int i=1;i<=100000;i++) //预处理
{
fac[i] = fac[i-1] * i % MOD;
infac[i] = (LL)infac[i-1] * qmi(i,MOD-2,MOD)%MOD;
}
cin>>n;
while(n--)
{
int a,b;
cin>>a>>b;
//多%几次 会爆
cout<<(LL)fac[a] * infac[b]%MOD * infac[a-b] %MOD<<endl;
}
}