hdu 5446 Lucas+中国剩余定理

传送门

题意:给你三个数n, m, k,第二行是k个数,p1,p2,p3...pk,所有p的值不相同且p都是质数,求C(n, m) % (p1*p2*p3*...*pk)的值

思路:

我们知道题目要求C(n, m) % (p1*p2*p3*...*pk)的值

其实这个就是中国剩余定理最后算出结果后的最后一步求余

那C(n, m)相当于以前我们需要用中国剩余定理求的值

然而C(n, m)太大,我们只好先算出

C(n, m) % p1 = r1

C(n, m) % p2 = r2

C(n, m) % p3 = r3

.

.

.

C(n, m) % pk = rk

用Lucas,这些r1,r2,r3...rk可以算出来

然后又是用中国剩余定理求答案
 

代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#define ll long long
using namespace std;
const int N = 100000 + 5;

ll fact(int n, ll p){//n的阶乘求余p 
    ll ret = 1;
     for (int i = 1; i <= n ; i ++) ret = ret * i % p ;
    return ret ;
}
void ex_gcd(ll a, ll b, ll &x, ll &y, ll &d){
    if (!b) {d = a, x = 1, y = 0;}
    else{
        ex_gcd(b, a % b, y, x, d);
        y -= x * (a / b);
    }
}
ll mul(ll a, ll b, ll p){//快速乘,计算a*b%p 
    ll ret = 0;
    while(b){
        if(b & 1) ret = (ret + a) % p;
        a = (a + a) % p;
        b >>= 1;
    }
    return ret;
}
ll inv(ll t, ll p){//如果不存在,返回-1 
    ll d, x, y;
    ex_gcd(t, p, x, y, d);
    return d == 1 ? (x % p + p) % p : -1;
}
ll china(int n, ll *a, ll *m){//中国剩余定理 
    ll M = 1, ret = 0;
    for(int i = 0; i < n; i ++) M *= m[i];
    for(int i = 0; i < n; i ++){
        ll w = M / m[i];
        //ret = (ret + w * inv(w, m[i]) * a[i]) % M;//这句写了会WA,用下面那句 
        ret = (ret + mul(w * inv(w, m[i]), a[i], M)) % M;
        //因为这里直接乘会爆long long ,所以要用快速乘
    }
    return (ret + M) % M;
}
ll comb(ll n, ll m, ll p){//C(n, m) % p
    if (m < 0 || m > n) return 0;
    return fact(n, p) * inv(fact(m, p), p) % p * inv(fact(n-m, p), p) % p;//组合数公式 n! / (m!*(n-m)!)
}
ll Lucas(ll n, ll m, ll p){
        return m ? Lucas(n/p, m/p, p) * comb(n%p, m%p, p) % p : 1;
}
int main(){
    int T, k;
    ll n, m, p[15], r[15];
    scanf("%d", &T);
    while(T--){
        scanf("%lld%lld%d", &n, &m, &k);
        for(int i = 0; i < k; i ++){
            scanf("%lld", &p[i]);
            r[i] = Lucas(n, m, p[i]);
        }
        printf("%lld\n", china(k, r, p));
    }
    return 0;
}

 

展开阅读全文

没有更多推荐了,返回首页