CC

自然万物都趋向从有序变得无序

0%

Saving Beans 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

Hint

    For sample 1, squirrels will put no more than 2 beans in one tree. Since trees are different, we can label them as 1, 2 … and so on. 
    The 3 ways are: put no beans, put 1 bean in tree 1 and put 2 beans in tree 1. For sample 2, the 3 ways are:
put no beans, put 1 bean in tree 1 and put 1 bean in tree 2.

题意:

从n个物品中选出不超过m个物品共有多少种方法.

思路:

Lucas定理 + 排列组合的插空法.

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<cmath>
using namespace std;

typedef long long LL;
LL f[100000+10];

void init(LL mod){
f[0]=1;
for(int i = 1;i <= mod+10; ++i)
f[i] = f[i-1] * i % mod;
}

LL qpow(LL x, LL n,LL mod){
LL ans = 1;
while(n){
if(n&1) ans =ans *x % mod;
x =x *x % mod;
n >>= 1;
}
return ans;
}

LL lucas(LL n,LL m,LL mod){
LL ans =1;
while(n&&m){
LL nn = n%mod;
LL mm = m %mod;
if(nn<mm) return 0;
ans = ans *f[nn] * qpow(f[mm]*f[nn-mm] % mod,mod- 2,mod) % mod;
n/=mod;
m/=mod;
}
return ans;
}

int main(){
int t;
scanf("%d", &t);
int kase = 0;
while(t--){
LL n,m,p;
scanf("%lld %lld %lld", &n, &m, &p);
init(p);
LL ans = lucas(n+m , n ,p);
printf("%lld\n",ans );
}
return 0;
}