Saving Beans
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2978 Accepted Submission(s): 1120
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.
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.
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 3HintHint 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.
Source
Recommend
解析:n棵树上挂 x beans的方案数实际上就是:x1+x2+...+xn=x的方案数。
设b[i]=x[i]+1,则有:b1+b2+.....bn=x+n
将 x+n 看成一条线段,将此线段分为 n 段的方案数即为解的个数,即为:C(n+x-1,n-1)=C(n+x-1,x);
综上:n棵树上挂不超过 m beans 的方案数就为:
ans=ans1+ans2+....+ansm
=C(n-1,0)+C(n,1)+C(n+1,2)+....+C(n+m-1,m)
=C(n,0)+C(n,1)+C(n+1,2)+......+C(n+m-1,m)
然后根据:C(n+1,r)=C(n,r-1)+C(n,r)
==>ans=C(n+m,m)
原问题就转化为求:C(n+m,m)%p的值,用lucas定理即可解决。
代码:
#include<cstdio>
#define maxn 100000
using namespace std;
typedef long long LL;
LL fac[maxn+20];
LL pow_mod(LL x,LL y,LL p)
{
LL ans=1;
while(y>0)
{
if(y&1)ans=ans*x%p;
x=x*x%p,y>>=1;
}
return ans;
}
LL lucas(LL n,LL m,LL p)
{
LL ans=1,a,b,c;
while(n && m)
{
a=n%p,b=m%p;
if(a<b)return 0;
c=fac[a]*pow_mod(fac[b]*fac[a-b]%p,p-2,p)%p;
ans=ans*c%p,n/=p,m/=p;
}
return ans;
}
int main()
{
LL n,m,p,t,i;
scanf("%I64d",&t);
while(t--)
{
scanf("%I64d%I64d%I64d",&n,&m,&p);
fac[0]=fac[1]=1;
for(i=2;i<=p;i++)fac[i]=fac[i-1]*i%p;
printf("%I64d\n",lucas(n+m,m,p));
}
return 0;
}