G - Unknown Treasure HDU - 5446
On the way to the next secret treasure hiding place, the mathematician discovered a cave unknown to the map. The mathematician entered the cave because it is there. Somewhere deep in the cave, she found a treasure chest with a combination lock and some numbers on it. After quite a research, the mathematician found out that the correct combination to the lock would be obtained by calculating how many ways are there to pick mm different apples among nn of them and modulo it with MM. MM is the product of several different primes.
Input
On the first line there is an integer T(T≤20)T(T≤20) representing the number of test cases.
Each test case starts with three integers n,m,k(1≤m≤n≤1018,1≤k≤10)n,m,k(1≤m≤n≤1018,1≤k≤10) on a line where kk is the number of primes. Following on the next line are kk different primes p1,...,pkp1,...,pk. It is guaranteed that M=p1⋅p2⋅⋅⋅pk≤1018M=p1·p2···pk≤1018 and pi≤105pi≤105 for every i∈{1,...,k}i∈{1,...,k}.
Output
For each test case output the correct combination on a line.
Sample Input
1 9 5 2 3 5
Sample Output
6
裸题 中国剩余定理
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=1e5+7;
ll fac[maxn],inv[maxn];
ll quickpow(ll a,ll b,ll mod)
{
ll ret=1;
while(b)
{
if(b&1) ret=(ret*a)%mod;
a=(a*a)%mod;
b>>=1;
}
return ret;
}
void init(int p)
{
fac[0]=1;
for(int i=1;i<=p;i++)
{
fac[i]=(fac[i-1]*i)%p;
}
inv[p-1]=quickpow(fac[p-1],p-2,p);
for(int i=p-2;i>=0;i--)
{
inv[i]=(inv[i+1]*(i+1))%p;
}
}
ll C(ll n,ll m,ll mod)
{
if (m > n || m < 0 || n < 0) return 0;
return fac[n]*inv[m]%mod*inv[n-m]%mod;
}
ll lucas(ll a,ll b,ll mod)
{
if(a<mod&&b<mod) return C(a,b,mod);
return C(a%mod,b%mod,mod)*lucas(a/mod,b/mod,mod)%mod;
}
ll mul(ll a,ll b,ll mod)
{
a=(a%mod+mod)%mod;
b=(b%mod+mod)%mod;
ll ret=0;
while(b)
{
if(b&1)
{
ret+=a;
if(ret>=mod) ret-=mod;
}
b>>=1;
a<<=1;
if(a>=mod) a-=mod;
}
return ret;
}
ll exgcd(ll a,ll b,ll &x,ll &y)
{
if(!b)
{
x=1,y=0;
return a;
}
ll d = exgcd(b, a % b, y, x);
y -= x * (a / b);
return d;
}
ll CRT(ll *a,ll *m,int n)
{
// ll M=1;
// ll ans=0;
// for(int i=0;i<n;i++) M*=m[i];
// for(int i=0;i<n;i++)
// {
// ll x=0,y=0;
// ll Mi=M/m[i];
// exgcd(Mi,m[i],x,y);
// ans=ans+mul(mul(Mi,x,M),a[i],M);
// }
// if(ans<0) ans+=M;
// return ans;
ll M = 1, d, y, x = 0;
for (int i = 0; i < n; i++) M *= m[i];
for (int i = 0; i < n; i++)
{
ll w = M / m[i];
exgcd(m[i], w, d, y);
x = (x + mul(mul(y, w, M), a[i], M));
}
return (x + M) % M;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
ll n,m,a[15],p[15];
int k;
scanf("%lld%lld%d",&n,&m,&k);
for(int i=0;i<k;i++)
{
scanf("%lld",&p[i]);
init(p[i]);
a[i]=lucas(n,m,p[i]);
}
printf("%lld\n",CRT(a,p,k));
}
return 0;
}