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)。
因為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;
}