HDU - 3037 I - Saving Beans

I - Saving Beans

HDU - 3037

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

       
 

Hint

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.

题目描述:

把不多于m颗豆,放在不同的n个树洞里面。

分析:

  首先插板法是:把m颗豆放进n个洞里,每个洞至少一颗。公式:C(m-1,n-1);

  先假设是有m颗豆,放在不同的n个树洞,每个树洞可能为空,先在n个树洞放n课豆,就转变成m颗豆放入n个树洞,每个树洞至少放一颗。

  先看不大于m颗的情况,我们可以增加一个洞用来存放 不放进n个树洞的豆,这样就实现不大于m的情况。

  多加的树洞也可能为空,也要先放一颗豆。

  综合上面,可以把问题转换成把m+n+1颗豆分n+1堆。

  就有公式C(n+1-1,m+n+1-1)=C(n,m+n)。(n-1在上,m+n-1在下)

插板法参考:https://blog.csdn.net/sdz20172133/article/details/81431066

  而n和m都是很大的树,我们可以先用lucas定理把他降到小于mod,再预处理阶乘,来计算组合数C(n,m+n);

代码:

#include<iostream> 
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
int p;
ll f[100007]={0};
ll mod_pow(ll x,ll n)
{
    if(n==0) return 1;
    ll res=1;
    x=x%p;
    while(n)
    {
        if(n&1) res=res*x%p;
        x=x*x%p;
        n>>=1;
    }
    return res;
}
ll C(ll m,ll n)
{
    if(m==0) return 1;
    if(m==n) return 1;
    //要加 
    if(m>n) return 0;
    ll ans=f[n]*(mod_pow(f[n-m]*f[m]%p,p-2)%p)%p;
    return ans;
}
ll lucas(ll a,ll b)
{
    if(a==0||b==0) return 1;
    if(a>=p||b>=p) return lucas(a/p,b/p)*C(a%p,b%p)%p;
    else return C(a,b);
}
int main()
{
    int T;
    cin>>T;
    f[0]=f[1]=1;
    while(T--)
    {
        ll n,m;
        scanf("%lld%lld%lld",&n,&m,&p);
        for(int i=2;i<=p;i++)
        {
            f[i]=f[i-1]*i%p;
        }
        ll fm=n+m;
        ll ans;
        ans=lucas(n,fm);
        printf("%lld\n",ans%p);
    }
    return 0;
}
 

猜你喜欢

转载自www.cnblogs.com/studyshare777/p/12242315.html