HDU 3037 Saving Beans (Lucas定理)

题目链接

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.

PS:题意:一共有n棵树,不超过m个果子,要将这些果子放到这些树里面,问有多少种放法(可以有树不放果子)。

题解:我们先考虑正好有m个果子有多少种放法,m个果子,n棵树的放法根据插板法得出为C(m+n-1,n-1)=C(m+n-1,m)。(插板法详解)。然后m-1的放法为C(m+n-2,m-1),当m等于0时的放法为C(n-1,0)。

所以总的放法为C(n-1,0)+……+C(m+n-1,m)。根据排列组合公式C(n,k) = C(n-1,k)+C(n-1,k-1)。得到最终结果为,C(m+n,m)。

扫描二维码关注公众号,回复: 4878029 查看本文章

因为p是质数,后面就是直接用Lucas定理了。

#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<map>
#include<queue>
#include<set>
#include<cmath>
#include<stack>
#include<string>
const int maxn=1e5+10;
const int mod=1e9+7;
const int inf=1e8;
#define me(a,b) memset(a,b,sizeof(a))
#define lowbit(x) x&(-x)
typedef long long ll;
using namespace std;
ll n,m,p,num[maxn];
void inct(ll p)
{
    num[0]=1;
    for(int i=1;i<=p;i++)
        num[i]=(i*num[i-1])%p;
}
ll quick_pow(ll a,ll b)
{
    ll temp=a%p,res=1;
    while(b)
    {
        if(b&1)
            res=res*temp%p;
        temp=temp*temp%p;
        b>>=1;
    }
    return res;
}
ll C(ll a,ll b)
{
    if(a<b)
        return 0;
    return num[a]*quick_pow(num[b]*num[a-b],p-2)%p;
}
ll Lucas(ll a,ll b)
{
    if(!b)
        return 1;
    return C(a%p,b%p)*Lucas(a/p,b/p)%p;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        scanf("%d%d%d",&n,&m,&p);
        inct(p);
        printf("%lld\n",Lucas(n+m,m));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41292370/article/details/84974837
今日推荐