S - Saving Beans
Although winter is far away, squirrels have to work day and night to save beans. They need plenty of food to get through those long cold days. After some time the squirrel family thinks that they have to solve a problem. They suppose that they will save beans in n different trees. However, since the food is not sufficient nowadays, they will get no more than m beans. They want to know that how many ways there are to save no more than m beans (they are the same) in n trees.
Now they turn to you for help, you should give them the answer. The result may be extremely huge; you should output the result modulo p, because squirrels can’t recognize large numbers.Input
The first line contains one integer T, means the number of cases.
Then followed T lines, each line contains three integers n, m, p, means that squirrels will save no more than m same beans in n different trees, 1 <= n, m <= 1000000000, 1 < p < 100000 and p is guaranteed to be a prime.Output
You should output the answer modulo p.
Sample Input
2 1 2 5 2 1 5Sample Output
3 3Hint
Hint For sample 1, squirrels will put no more than 2 beans in one tree. Since trees are different, we can label them as 1, 2 … and so on. The 3 ways are: put no beans, put 1 bean in tree 1 and put 2 beans in tree 1. For sample 2, the 3 ways are: put no beans, put 1 bean in tree 1 and put 1 bean in tree 2.
思路:卢卡斯定理对于求组合数较大时非常适用,如求从n个不同球中取m个球有多少方案,C(n,m)=?,当n,m比较小时可以用
C(n,m)=C(n-1,m)+C(n-1,m-1) (即对于一个球的行为为取或不取)用一个for循环即可求出,而本题的n的限制条件过大,又要求对结果模一个质数p,那么卢卡斯定理就派上用场了。
令,n=ap+rn,m=bp+rm,rm=m%p,rn=n%p;
那么有C(n,m)=C(a,b)*C(rn,rm)%p;
当a<p且b<p时结束递归。
另外,本题还用到费马小定理。
费马小定理求逆元:
在模为素数p的情况下,有费马小定理
a^(p-1)=1(mod p)
那么a^(p-2)=a^-1(mod p)
也就是说a的逆元1/a=1/a*aa^(p-1)=a^(p-2)
#include<cstdio>
#include<stack>
#include<set>
#include<vector>
#include<queue>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<iostream>
#include<cmath>
using namespace std;
#define inf 0x3f3f3f3f
typedef long long ll;
const int N=100005;
const int MOD = 1e9 + 7;
ll n,m,q;
ll num[N];
void mul()
{
num[0]=1;
num[1]=1;
for(ll i=2; i<=q; i++)
num[i]=(i*num[i-1])%q;
}
ll pows(ll x,ll k)
{
ll a=x,ans=1;
while(k)
{
if(k&1) ans=(ans*a)%q;
a=(a*a)%q;
k/=2;
}
return ans;
}
ll C(ll a,ll b)
{
if(a<b)
return 0;
if(b==0)
return 1;
return num[a]*pows(num[b]*num[a-b]%q,q-2)%q;
}
ll kalus(ll a,ll b)
{
if(a<q&&b<q)
return C(a,b)%q;
return C(a%q,b%q)%q*kalus(a/q,b/q)%q;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n>>m>>q;
mul();
ll ans=kalus(n+m,m);
cout<<ans<<endl;
}
return 0;
}