HDU 5446 Unknown Treasure【Lucas+中国剩余定理】

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=5446

题意:

求$n \choose {m}$$mod M$,其中$0 \le n,m \le 1e18$ 且$M$可以拆成不同质数的积。

分析:

板子,Lucas + 中国剩余定理

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*************************************************************************
> File Name: 5446.cpp
> Author: jiangyuzhu
> Mail: 834138558@qq.com
> Created Time: 2016/9/23 14:47:11
************************************************************************/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 10 + 5;
ll p[maxn], a[maxn];
ll fact(int n, ll mod)
{
ll ans = 1;
for(int i = 1; i <= n; i++){
ans = i * 1ll * ans % mod;
}
return ans;
}
ll extgcd(ll a, ll b, ll &x, ll &y)
{
ll d = a;
if(b != 0) {
d = extgcd(b, a % b, y, x);
y -= (a/b) * x;
}else {
x = 1, y = 0;
}
return d;
}
ll comb(ll n, ll m, ll p)
{
if(m < 0 || m > n) return 0;
ll x, y;
extgcd(fact(m, p), p, x, y);
ll xx, yy;
extgcd(fact(n - m, p), p, xx, yy);
return fact(n, p) * x % p * xx % p;
}
ll lucas(ll n, ll m, ll p)
{
return m ? lucas(n / p, m / p, p) * comb(n % p, m % p, p) % p: 1;
}
ll quick_mul(ll a, ll k, ll mod)
{
ll ans = 0;
for(; k; k >>= 1, a = (a + a) % mod){
if(k & 1) ans = (ans + a) % mod;
}
return ans;
}
ll China(int n)
{
ll M = 1, ans = 0;
ll tmp;
for(int i = 0; i < n; i++) M *= p[i];
for(int i = 0; i < n; i++){
tmp = M / p[i];
ll x, y;
extgcd(tmp, p[i], x, y);
x = (x % p[i] + p[i]) % p[i];
ans = ((ans + quick_mul(a[i] * tmp % M, x, M) % M) + M) % M;
}
return ans;
}
int main (void)
{
int T;scanf("%d", &T);
while(T--){
ll n, m;
int k;
scanf("%lld%lld%d", &n, &m, &k);
for(int i = 0; i < k; i++){
scanf("%lld", &p[i]);
a[i] = lucas(n, m, p[i]);
}
printf("%lld\n", China(k));
}
return 0;
}
文章目录
  1. 1. 题目链接:
  2. 2. 题意:
  3. 3. 分析:
  4. 4. 代码: