crf 出生的第一秒
1 Description
crf 是一个天才。
他出生的第一秒,就已经学完了整本《组合数学》。
他觉得作为高中生的你,应该比才出生一秒的他差不到哪去,于是他决定向你问一个问题。
crf 想知道,从n 个物品中选出m 个的方案数,由于他很讨厌很长的答案,所以他想知道模p
后的答案。
2 Input
输入的第一行为三个整数n; m; p。
3 Output
输出共一行,为一个数字,代表答案。
4 Sample
Sample Input
5 3 7
Sample Output
3
Sample Input
125 77 71
Sample Output
63
5 Hint
对于30% 的数据,满足1 <= m , n <= 10; 1 <= p <=10。
对于70% 的数据,满足1 <= m , n <= 100000。
对于100% 的数据,满足1 <= m , n <= 1000000000; 1 <= p <= 100000。
对于100% 的数据,满足p 为质数。
#include <cstdio>
#include <iostream>
#define LL long long
using namespace std;
const LL N = 1e6 + 3;
LL mub[N+10];
LL x, y;
LL n, m ,p;
void init(){
mub[0] = 1;//
for(register int i=1; i<=N+5; i++){
mub[i] = mub[i-1] * i % p;
}
}
LL exgcd(LL a, LL b, LL &x, LL &y){
if(a == 0 && b == 0)
return -1;
if(b == 0){
x = 1; y = 0;
return a;
}
LL d = exgcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
LL mod_reverse(LL a, LL n){
LL d = exgcd(a, n, x, y);
if(d == 1) return ( x % n + n ) % n;
else return -1;
}
LL solve(LL a, LL b){
if(a > b) return 0;
LL nn = mod_reverse((mub[a] * mub[(b + p - a) % p]) % p, p);
return mub[b] * nn % p;
}
void to_solve(LL a, LL b){
if(b < p){
solve(a, b); return;
}
cout << (solve(a/p, b/p) * solve(a%p, b%p) % p + p ) % p << endl;
// printf("%I64d\n", (solve(a/p, b/p) * solve(a%p, b%p) % p + p ) % p );
}
int main(){
freopen ("first.in", "r", stdin);
freopen ("first.out", "w", stdout);
scanf("%I64d%I64d%I64d", &n, &m, &p);
init();
if(n < p){
cout << ( solve(m, n) % p + p ) % p << endl;
//printf("%I64d\n", ( solve(m, n) % p + p ) % p );
}
else to_solve(m, n);
return 0;
}