東北育才 DAY2組合數取mod (comb)
阿新 • • 發佈:2017-06-19
cin 數據規模 問題 quick -m turn stream i++ printf
組合數取模(comb)
【問題描述】
計算C(m,n)mod 9901的值
【輸入格式】
從文件comb.in中輸入數據。
輸入的第一行包含兩個整數,m和n
【輸出格式】
輸出到文件comb.out中。
輸出一行,一個整數
【樣例輸入】
2 1
【樣例輸出】
2
【數據規模與約定】
對於 20%的數據,n<=m<=20
對於 40%的數據,n<=m<=2000
對於 100%的數據,n<=m<=20000
這道題描述很清楚,有很多種做法,第一題還是挺水的,而且很多網站上也有
自己比較懶,因為摸的數很小,寫了一個半打表半lucas。
#include<iostream> #include<cstring> #include<cstdio> using namespace std; int C[9902][9902]; int main() { int i,j; int n,m; cin>>n>>m; for(i=0;i<=9901;i++) { C[i][i]=1; C[i][1]=1; C[i][0]=1; } for(i=2;i<=9901;i++) { for(j=1;j<=i;j++) { C[i][j]=((C[i-1][j-1])%9901+(C[i-1][j])%9901)%9901; } } int ans=0; ans=(C[n/9901][m/9901]*C[n%9901][m%9901])%9901; cout<<ans; }
還有一種是直接lucas..
#include<iostream> #include<cstring> #include<cstdio> using namespacestd; typedef long long LL; LL n,m,p; LL quick_mod(LL a, LL b) { LL ans=1; a%=p; while(b) { if(b&1) { ans=ans*a%p; b--; } b>>=1; a=a*a%p; } return ans; } LL C(LL n, LL m) { if(m>n) return 0; LL ans=1; for(int i=1; i<=m; i++) { LL a=(n+i-m)%p; LL b=i%p; ans=ans*(a*quick_mod(b,p-2)%p)%p; } return ans; } LL Lucas(LL n, LL m) { if(m == 0) return 1; return C(n%p,m%p)*Lucas(n/p,m/p)%p; } int main() { scanf("%lld%lld", &n, &m); p=9901; printf("%lld\n", Lucas(n,m)); return 0; }
還有一種是直接打表..這裏發一下我旁邊dalao寫的程序
#include<iostream> #include<cstring> #include<cstdio> using namespace std; typedef long long LL; LL n,m,p; LL quick_mod(LL a, LL b) { LL ans=1; a%=p; while(b) { if(b&1) { ans=ans*a%p; b--; } b>>=1; a=a*a%p; } return ans; } LL C(LL n, LL m) { if(m > n) return 0; LL ans = 1; for(int i=1; i<=m; i++) { LL a = (n + i - m) % p; LL b = i % p; ans = ans * (a * quick_mod(b, p-2) % p) % p; } return ans; } LL Lucas(LL n, LL m) { if(m == 0) return 1; return C(n % p, m % p) * Lucas(n / p, m / p) % p; } int main() { scanf("%lld%lld", &n, &m); p=9901; printf("%lld\n", Lucas(n,m)); return 0; }
東北育才 DAY2組合數取mod (comb)