寒假训练数论I / HDU - 3037

题目
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
题目大意
有m颗豆子,求将不超过m个豆子放到n棵树的方案数。
(即将i(i=0,1,2,3…m-1,m)颗豆子放到n棵树的总方案数)
(允许有树不放豆子,由于答案很大,%p)。
(1 <= n, m <= 1000000000, 1 < p < 100000)
解题思路
插板法
将不超过m颗豆子放到n棵树,那么我们可以将这m颗豆子分成n+1分(因为"不超过m颗豆子",所以要舍去一份)

一共n+m个圈,在其中选n个圈(标成红色)
在这里插入图片描述
这些红色的圈相当于隔板,将剩下的m个圈分成了n+1份。
不妨将最后一份当做要舍去的那一份,
则前面n份对应的数量对应着n棵树的状态。
所以答案是C(m+n,n)
由于m,n很大,p是质数。
用到Lucas定理
Lucas定理:
C(m,n)≡C(m%p,n%p)*C(m/p,n/p) (mod p)
代码

#include 
#include 
using namespace std;
long long p;
long long a[101010];
long long MI(long long a,long long b)
{
	long long ans=1;
	long long base=a;
	while (b)
	{
		if (b&1) ans=(ans*base)%p;
		base=(base*base)%p;
		b>>=1;
	}
	return ans;
}
long long C(long long m,long long n)
{
	if (m<n) return 0;
	if (m==n || n==0) return 1;
	if (n==1) return m;
	return ((a[m]*MI(a[n],p-2))%p*MI(a[m-n],p-2))%p;
}
long long Lucas(long long m,long long n)
{
	if (n==0) return 1;
	return ((C(m%p,n%p)*Lucas(m/p,n/p))%p);
}
int main()
{
	int T;
	cin>>T;
	while (T--)
	{
		long long aa,bb;
		cin>>aa>>bb>>p;
		a[0]=1;
	    for (int i=1;i<=p;i++) 
		   a[i]=(a[i-1]*i)%p;
		long long ans=Lucas(aa+bb,aa);
		cout<<ans<<endl;
	}
}

你可能感兴趣的:(寒假训练数论I / HDU - 3037)