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

28 篇文章 0 订阅

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+m1 ,又因为豆子可以不全部用上,所以m的取值范围为[0,m],即总方法数为 C0n1+C1n+C2n+1++Cmn+m1=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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值