题目
http://acm.hdu.edu.cn/showproblem.php?pid=3037
-
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
3
3
题意
有n棵存放食物的树,每棵树都可以存放非负数量的食物,使得储存的食物小于等于m,求所有方案数并mod p
思路
利用隔板法,设放入了k个球(0<=k<=m),本来有n个球,则一共有n+k个球,一共有n-1个板(两边不放板,隔出来即是n棵树),每个板最少要隔一个球,有n+k-1个空格,则有C(n+k-1,n-1)种放板法。
总数量sum即是k从0取到m,sum=C(n+0-1,n-1)+C(n+1-1,n-1)+…+C(n+m+1,n-1)
用C(i,j)=C(i-1,j-1)+C(i,j-1)化简为sum=C(n+m,n)
数据比较大,用卢卡斯计算C(n,m)%p
代码
#include <iostream>
typedef long long ll;
using namespace std;
int MOD;
ll f[100010];
void fac(int p)
{ //f[n] = n!
f[0] = 1;
for (int i=1; i<=p; ++i) f[i] = f[i-1] * i % p;
}
ll pow_mod(ll a, ll x, int p)
{
ll sum = 1;
while (x)
{
if (x & 1)
sum = sum * a % p;
a = a * a % p;
x >>= 1;
}
return sum;
}
ll Lucas(ll n, ll k, int p) //C (n, k) % p
{
ll ret = 1;
while (n && k)
{
ll nn = n % p, kk = k % p;
if (nn < kk) return 0;
//inv (f[kk]) = f[kk] ^ (p-2) % p
ret= ret* f[nn]* pow_mod (f[kk]* f[nn-kk]% p, p-2, p)% p;
n /= p, k /= p;
}
return ret;
}
int main() {
int t,n,m,p;
cin>>t;
while(t--) {
cin>>n>>m>>p;
fac(p);
printf ("%lld\n", Lucas (n+m, m, p));
}
return 0;
}