HDU 3037 Saving Beans(组合数学+Lucas定理)
2017-11-26 22:01
429 查看
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的豆子,问有多少种方法解题思路
当所有m个豆子都放上时,有a1+a2+……+an=m,根据插板法可得在这种情况的方法数有Cmn+m−1,又因为豆子可以不全部用上,所以m的取值范围为[0,m],即总方法数为C0n−1+C1n+C2n+1+……+Cmn+m−1=Cmn+m,又因为n的范围太大,所以需要借助Lucas定理进行转化.即lucas(n,m,p)=lucas(n/p,m/p,p)*C(n%p,m%p,p),
lucas(n,0,p)=1。
代码实现
#include<bits/stdc++.h> using namespace std; #define ll long long ll quick_pow(ll a,ll b,ll p) { ll ans=1; a%=p; while(b>0) { if(b%2) ans=ans*a%p; a=a*a%p; b/=2; } return ans; } ll calc(int n,int m,int p) { ll a=1,b=1; if(m>n) return 0; while (m) { a=a*n%p; b=b*m%p; n--; m--; } return a*quick_pow(b,p-2,p)%p; } ll lucas(ll n,ll m,ll p) { if(m==0) return 1; return calc(n%p,m%p,p)*lucas(n/p,m/p,p)%p; } int main() { ios::sync_with_stdio(false); int T; ll n,m,p; cin>>T; while(T--) { cin>>n>>m>>p; ll ans=0; ans=(ans+lucas(n+m,m,p))%p; cout<<ans<<endl; } return 0; }
相关文章推荐
- hdu 3037 Saving Beans(组合数学+lucas定理)
- HDU 3037 Saving Beans【Lucas定理】【模板题】【模板】【组合数取余】
- hdu 3037 lucas定理-组合数学 hdu 4399
- HDU 3037 Saving Beans 组合数取模 Lucas定理
- HDU 3037 Saving Beans 大组合数 lucas定理
- HDU 3037 Saving Beans(Lucas定理的直接应用)
- hdu-3037-组合数取模-Lucas定理
- hdu 3037 Saving Beans(组合数学)
- [ACM] hdu 3037 Saving Beans (Lucas定理,组合数取模)
- hdu 3037 Saving Beans(组合数学)
- HDU 3037 Saving Beans(Lucas定理的直接应用)
- hdu-3037-Saving Beans(Lucas定理+大组合数取模)
- HDU 3037 Saving Beans (Lucas定理)
- hdu 3037 Saving Beans(lucas定理)(卢卡斯定理)
- HDU 3037 Saving Beans(Lucas定理的直接应用)
- hdu 3037 Saving Beans (大组合数取模--Lucas定理)
- hdu 3037 排列组合+Lucas定理
- HDU 3037 Saving Beans [Lucas定理]
- HDU 3037 Saving Beans(lucas定理)
- [HDU 3037] Saving Beans (隔板法+lucas定理)