您的位置:首页 > 其它

HDU 3037 Saving Beans(组合数学+Lucas定理)

2017-11-26 22:01 429 查看

Problem Description

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 5


Sample Output

3
3


题目大意

在n棵树上放置不超过m的豆子,问有多少种方法

解题思路

当所有m个豆子都放上时,有a1+a2+……+an=m,根据插板法可得在这种情况的方法数有Cmn+m−1,又因为豆子可以不全部用上,所以m的取值范围为[0,m],即总方法数为C0n−1+C1n+C2n+1+……+Cmn+m−1=Cmn+m,又因为n的范围太大,所以需要借助Lucas定理进行转化.

即lucas(n,m,p)=lucas(n/p,m/p,p)*C(n%p,m%p,p),

lucas(n,0,p)=1。

代码实现

#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll quick_pow(ll a,ll b,ll p)
{
ll ans=1;
a%=p;
while(b>0)
{
if(b%2)
ans=ans*a%p;
a=a*a%p;
b/=2;
}
return ans;
}
ll calc(int n,int m,int p)
{
ll a=1,b=1;
if(m>n) return 0;
while (m)
{
a=a*n%p;
b=b*m%p;
n--;
m--;
}
return a*quick_pow(b,p-2,p)%p;
}
ll lucas(ll n,ll m,ll p)
{
if(m==0)
return 1;
return calc(n%p,m%p,p)*lucas(n/p,m/p,p)%p;
}
int main()
{
ios::sync_with_stdio(false);
int T;
ll n,m,p;
cin>>T;
while(T--)
{
cin>>n>>m>>p;
ll ans=0;
ans=(ans+lucas(n+m,m,p))%p;
cout<<ans<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: