天天看點

hdu3037 Saving Beans (lucas定理+組合數公式)

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.

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

Hint

Source

​​2009 Multi-University Training Contest 13 - Host by HIT​​

Recommend

gaojie   |   We have carefully selected several similar problems for you:  

​​3033​​​ 

​​​3038​​​ 

​​​3036​​​ 

​​​3035​​​ 

​​​3034​​ 

解析: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;
}