組合數

Problem 2020 組合

Accept: 1216    Submit: 2914
Time Limit: 1000 mSec    Memory Limit : 32768 KB

 Problem Description

給出組合數C(n,m), 表示從n個元素中選出m個元素的方案數。例如C(5,2) = 10, C(4,2) = 6.可是當n,m比較大的時候,C(n,m)很大!於是xiaobo希望你輸出 C(n,m) mod p的值!

 Input

輸入數據第一行是一個正整數T,表示數據組數 (T <= 100) 接下來是T組數據,每組數據有3個正整數 n, m, p (1 <= m <= n <= 10^9, m <= 10^4, m < p < 10^9, p是素數)

 Output

對於每組數據,輸出一個正整數,表示C(n,m) mod p的結果。

 Sample Input

25 2 35 2 61

 Sample Output

110

 Source

FOJ有獎月賽-2011年04月(校賽熱身賽)


這題是個求組合數的題,求C(n,m) mod p;可以直接使用lucas定理直接過;快速冪求個逆元;


#include <iostream>  
#include <cstdio>  
using namespace std;  
typedef long long LL;  
LL n,m,p;  
LL power(LL a,LL b){  
    LL ans=1,temp=a%p;  
    while(b){  
        if(b&1) ans=ans*temp%p;  
        temp=temp*temp%p;  
        b>>=1;  
    }  
    return ans;  
}  
LL cal(LL a,LL b){ // Cm(a,b)=(a!/(a-b)!) * (b!)^(p-2)) mod p  
    if(b>a) return 0; // important  
    LL ans=1;  
    for(int i=1;i<=b;i++){  
        LL t1=(a-b+i)%p,t2=i%p;  
        ans=ans*(t1*power(t2,p-2)%p)%p;  
    }  
    return ans;  
}  
/*Lucas(n,m,p)=Cm(n%p,m%p)* Lucas(n/p,m/p,p) 
Lucas(x,0,p)=1;*/  
LL lucas(LL t1,LL t2){  
    if(t2==0) return 1;  
    return cal(t1%p,t2%p)*lucas(t1/p,t2/p)%p;  
}  
int main()  
{  
    //freopen("cin.txt","r",stdin);  
    int t;  
    cin>>t;  
    while(t--){  
        scanf("%lld%lld%lld",&n,&m,&p);  
        printf("%lld\n",lucas(n,m));  
    }  
    return 0;  
}  
人一我百!人十我萬!永不放棄~~~懷着自信的心,去追逐夢想。


發佈了74 篇原創文章 · 獲贊 11 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章