AcWing 885~888 求组合数

组合数各种性质及定理

//方法1  把每个Cab通过递推式预处理(n<=1e4,b<=a<=2e3)
#include<bits/stdc++.h>
using namespace std;

const int N = 2010,mod = 1e9+7;

int C[N][N];

void init(){
    for(int i=0;i<N;i++){
        for(int j=0;j<=i;j++){
            if(j==0) C[i][j]=1;
            else C[i][j]=(C[i-1][j]+C[i-1][j-1])%mod;
        }
    }
}

int main(){
    ios::sync_with_stdio(false);
    init();
    int n;
    cin>>n;
    while(n--){
        int a,b;
        cin>>a>>b;
        cout<<C[a][b]<<endl;
    }
    return 0;
}



//方法2  预处理阶乘和阶乘逆元(n<=1e4,b<=a<=1e5)
int main(){
    fact[0]=infact[0]=1;
    for(int i=1;i<=N;i++){
        fact[i]=(LL)fact[i-1]*i%mod;
        infact[i]=(LL)infact[i-1]*qpow(i,mod-2,mod)%mod;
    }
    
    //for(int i=0;i<=10;i++) cout<<fact[i]<<" "<<infact[i]<<endl;
    
    int n;
    cin>>n;
    while(n--){
        int a,b;
        cin>>a>>b;
        cout<<(LL)fact[a]*infact[b]%mod*infact[a-b]%mod<<endl;
    }
    return 0;
}

//方法3 卢卡斯定理(n<=20,b<=a<=1e18,p<1e5)

#include<bits/stdc++.h>
using namespace std;

typedef long long LL;

int p;

int qpow(int x,int y){
    int res=1;
    while(y){
        if(y&1) res=(LL)res*x%p;
        x=(LL)x*x%p;
        y>>=1;
    }
    return res;
}

int C(int a,int b){
    int res=1;
    for(int i=1,j=a;i<=b;i++,j--){
        res=(LL)res*j%p;
        res=(LL)res*qpow(i,p-2)%p;
    }
    return res;
}

int lucas(LL a,LL b){
    if(a<p && b<p) return C(a,b)%p;
    return (LL)C(a%p,b%p)*lucas(a/p,b/p)%p;
}

int main(){
    LL a,b;
    int n;
    
    cin>>n;
    while(n--){
        LL a,b;
        cin>>a>>b>>p;
        cout<<lucas(a,b)<<endl;
    }
    return 0;
}

//方法4 高精度(n=1,b<=a<=5000)
//get()函数:在 1~n 中,至少包含一个质因子 p 的有 n / p 个,至少包含两个质因子 p 的有 n / p^2 个,不过其中一个因子已经在 n / p 里已经统计过了,所以只需要在统计另一个 p ,即累加上 n / p^2。时间复杂度为O(nlogn)。
#include<bits/stdc++.h>
using namespace std;

const int N = 5010;

int primes[N],st[N],sum[N];

int get_primes(int n){
    int cnt=0;
    for(int i=2;i<=n;i++){
        if(!st[i]) primes[cnt++]=i;
        for(int j=0;primes[j]*i<=n;j++){
            st[primes[j]*i]=1;
            if(i%primes[j]==0) break;
        }
    }
    return cnt;
}

int get(int n,int p){
    int res=0;
    while(n){
        res+=n/p;
        n/=p;
    }
    return res;
}

vector<int> mul(vector<int> a,int b){
    int c=0;
    vector<int> res;
    for(int i=0;i<a.size();i++){
        c+=a[i]*b;
        res.push_back(c%10);
        c/=10;
    }
    while(c){
        res.push_back(c%10);
        c/=10;
    }
    return res;
}

int main(){
    int a,b;
    cin>>a>>b;
    int nums=get_primes(a);
    for(int i=0;i<nums;i++){
        int p=primes[i];
        sum[p]=get(a,p)-get(b,p)-get(a-b,p);
    }
    vector<int> res;
    res.push_back(1);
    for(int i=0;i<nums;i++){
        int p=primes[i];
        for(int j=0;j<sum[p];j++)
            res=mul(res,p);
    }
    for(int i=res.size()-1;i>=0;i--) cout<<res[i];
    return 0;
}




posted @ 2022-05-11 14:37  xhy666  阅读(45)  评论(0)    收藏  举报