题目:http://acm.hdu.edu.cn/showproblem.php?pid=3037
题意:n棵树上放最多m东西(东西都一样),问有多少种方法。答案模p。
转换为:在n个数相加不大于m的方法有多少种。
我们假设,n个数相加刚好等于m。插板法可以得出C(n+m-1,m);
那么不大于m的就是C(n+i-1,i)。0<=i<=m;
得出结果为C(n+m,m);
所以该题答案应该为C(n+m,m)%p;
因为要组合数又要取模,所以我们运用lucass定理。lucass定理就是用来计算C(n,m)%p这样的情况。p在1E5都范围内适用。在传统求组合的算法中,运用公式求解会无法处理大数据,因为模运算除法不适用。所以就要用逆元来将除法变乘法。也就是lucass定理。
#include<bits/stdc++.h>
#define PI 3.1415926
#define INF 1e18
#define inf 1e9
#define min(a,b) a<b?a:b
#define max(a,b) a>b?a:b
using namespace std ;
typedef long long ll;
typedef unsigned long long ull;
const int _max = 100000+100;
ll my_pow(ll x,int n,int p){
ll ret = 1;
while(n){
if(n&1) ret = ret*x%p;
x = x*x%p;
n>>=1;
}
return ret;
}
ll C(ll n,ll m,ll p){
ll a,b;
a=b=1;
if(m>n)
return 0;
while(m){
a=(a*n)%p;
b=(b*m)%p;
m--;
n--;
}
return (a*my_pow(b,p-2,p))%p;//利用逆元求C(n,m)%p;
}
ll lucass(ll n,ll m,ll p){
if(m==0)
return 1;
return (C(n%p,m%p,p)*lucass(n/p,m/p,p))%p;
}
int main(){
int n,m,p,t;
cin >> t;
while(t--){
cin>>n>>m>>p;
cout<<lucass(n+m,m,p)<<endl;;
}
return 0;
}