hdu 3037 Saving Beans (卢卡斯定理)

来源:互联网 发布:js json添加元素 编辑:程序博客网 时间:2024/05/16 11:12

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

# include <cstdio># include <iostream>using namespace std;typedef long long ll;const int MAXN = 100010;ll fac[MAXN];ll pow (int a, int n, int p)//快速幂{    ll A = a, ret = 1;    while (n)    {        if (n & 1)            ret = (ret * A) % p;        A = (A*A) % p;        n >>= 1;    }    return ret;}void init (int p)//初始化{    fac[0] = 1;    for (int i=1; i<=p; ++i)        fac[i] = i * fac[i-1]%p;}ll lucus (ll a, ll b, ll p)//卢卡斯定理{    ll ret = 1;    while (a && b)    {        ll aa = a%p, bb = b%p;        if (aa < bb) return 0;        ret = ret * fac[aa] * pow(fac[bb] * fac[aa-bb] % p, p-2, p) % p;        a /= p;        b /= p;    }    return ret;}int main (){    int T;    cin >> T;    while (T--)    {        ll n, m, p;        cin >> n >> m >> p;        init (p);        cout << lucus(n+m, m, p) << endl;    }    return 0;}
0 0