【ACWing】886. 求组合数 II

题目地址:

https://www.acwing.com/problem/content/888/

给定 n n n组询问,每次询问给定两个正整数 a a a b b b,求 ( a b ) a\choose b (ba)。答案模 1 0 9 + 7 10^9+7 109+7返回。

数据范围:
1 ≤ n ≤ 10000 1\le n\le 10000 1n10000
1 ≤ b ≤ a ≤ 1 0 5 1\le b\le a\le 10^5 1ba105

直接用公式。我们的目标是求出 ( a b ) m o d    ( 1 0 9 + 7 ) {a\choose b} \mod (10^9+7) (ba)mod(109+7),而 1 0 9 + 7 10^9+7 109+7是个素数。令 p = 1 0 9 + 7 p=10^9+7 p=109+7,那么我们要求 a ! ( a − b ) ! b ! m o d    p \frac{a!}{(a-b)!b!}\mod p (ab)!b!a!modp。可以预处理出来 n ! m o d    p n!\mod p n!modp ( n ! ) − 1 m o d    p (n!)^{-1}\mod p (n!)1modp,而预处理这个,可以通过递推关系来做。因为 n ! = ( n − 1 ) ! n n!=(n-1)!n n!=(n1)!n,而 ( n ! ) − 1 = ( ( n − 1 ) ! ) − 1 ( n ) − 1 (n!)^{-1}=((n-1)!)^{-1}(n)^{-1} (n!)1=((n1)!)1(n)1(这里的逆是指模 p p p的逆),所以每次只需要算 n − 1 n^{-1} n1即可。关于模素数 p p p的逆元求法,可以参考https://blog.csdn.net/qq_46105170/article/details/113823892。回答询问的时候,只需要输出 a ! ( ( a − b ) ! ) − 1 ( b ! ) − 1 m o d    p a!((a-b)!)^{-1}(b!)^{-1}\mod p a!((ab)!)1(b!)1modp。代码如下:

#include <iostream>
using namespace std;

const int N = 100010, mod = 1e9 + 7;

int fact[N], infact[N];

int fast_pow(int a, int k, int p) {
    
    
    int res = 1;
    while (k) {
    
    
        if (k & 1) res = (long) res * a % p;
        a = (long) a * a % p;
        k >>= 1;
    }

    return res;
}

int main() {
    
    
    fact[0] = infact[0] = 1;
    for (int i = 1; i < N; i++) {
    
    
        fact[i] = (long) fact[i - 1] * i % mod;
        infact[i] = (long) infact[i - 1] * fast_pow(i, mod - 2, mod) % mod;
    }

    int n;
    cin >> n;
    while (n--) {
    
    
        int a, b;
        cin >> a >> b;
        cout << ((long) fact[a] * infact[b] % mod * infact[a - b] % mod) << endl;
    }

    return 0;
}

预处理时间复杂度 O ( N log ⁡ p ) O(N\log p) O(Nlogp),每次询问 O ( 1 ) O(1) O(1),空间 O ( N ) O(N) O(N) N N N是输入参数范围。

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/113967216
今日推荐