常数复杂度求组合数

题目链接:http://acm.hdu.edu.cn/contests/contest_showproblem.php?pid=1001&cid=809

常数复杂度求组合数

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long LL;
const int maxn = 5e5;
const long long mod = 998244353;
LL A[maxn];
LL B[maxn];
void Init()
{
    A[0] = 1;
    for(int i=1; i<=maxn; i++){
        A[i] = (A[i-1] * i ) % mod;
    }
}

LL Ext_Gcd(LL a, LL b, LL &x, LL &y)
{
    if(b==0){
        x=1;
        y=0;
        return a;
    }
    LL d = Ext_Gcd(b, a%b, y, x);
    y-=a/b*x;
    return d;
}

LL Inv(LL a, LL n)
{
    LL x,y;
    LL d = Ext_Gcd(a,n,x,y);
    if(d == 1)
        return ((x%n)+n)%n;
    return -1;
}
LL get()
{
    for(int i=0;i<maxn;i++)
        B[i] = Inv(A[i],mod);
}
LL C(LL a, LL b, LL mod)
{
    if(a < b)
        return 0;
    return (A[a] * B[b] %mod)*B[a-b]%mod;
}
inline LL mmp(int x)
{
    if(x & 1)
        return -1;
    else
        return 1;
}
int main()
{
    Init();
    get();
    int t, n, m, k;
    cin>>t;
    while(t--)
    {
        cin>>n>>m>>k;
        int u = k / n;
        long long sum = 0;
        for(int i = 0; i <= u; ++i)
        {
            if(k + m - 1 - i * n > 0)
            sum += C(m, i, mod) * C(k+m-1-i*n, m-1, mod) * mmp(i) ;
            sum %= mod;
            if(sum < 0)
                sum += mod;
        }
        cout<<sum<<endl;
    }
    return 0;
}

貌似这个方法求C(m,n),m和n的范围只能到5e5,太大了会超时,不过询问的时候可以常熟出结果,我也不是很懂......

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long LL;
const int maxn = 5e5;
const long long mod = 998244353;
LL A[maxn];
LL B[maxn];
void Init()
{
    A[0] = 1;
    for(int i=1; i<=maxn; i++){
        A[i] = (A[i-1] * i ) % mod;
    }
}

LL Ext_Gcd(LL a, LL b, LL &x, LL &y)
{
    if(b==0){
        x=1;
        y=0;
        return a;
    }
    LL d = Ext_Gcd(b, a%b, y, x);
    y-=a/b*x;
    return d;
}

LL Inv(LL a, LL n)
{
    LL x,y;
    LL d = Ext_Gcd(a,n,x,y);
    if(d == 1)
        return ((x%n)+n)%n;
    return -1;
}
LL get()
{
    for(int i=0;i<maxn;i++)
        B[i] = Inv(A[i],mod);
}
LL C(LL a, LL b, LL mod)
{
    if(a < b)
        return 0;
    return (A[a] * B[b] %mod)*B[a-b]%mod;
}
inline LL mmp(int x)
{
    if(x & 1)
        return -1;
    else
        return 1;
}
int main()
{
    Init();
    get();
    int t, n, m, k;
    cin>>t;
    int t1,t2;
    while(t--)
    {
        scanf("%d%d",&t1,&t2);
        cout<<C(t1,t2,mod)<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/flyzer/article/details/81706311
今日推荐