hdu 6114 Chess(组合数取模)(Lucas定理)

本文介绍了一个关于国际象棋中車摆放的问题,并提供了一种高效的算法解决方案。通过组合数学中的组合公式来计算在特定尺寸的棋盘上最多能放置多少個車及其摆放方案的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Chess

题目链接:Chess

思路:设长边为n,短边为m,则题意为最多摆放m个車有多少种方案。
即从1~n中选m个数,也就是C(n,m)

代码:

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

typedef long long LL;
const int maxn=1e3+10;
const int mod=1e9+7;

LL qmod(LL a,LL n,LL p)
{
    int ans=1;
    while(n)
    {
        if(n&1)
            ans=ans*a%p;
        a=a*a%p;
        n>>=1;
    }
    return ans;
}

LL Comb(LL n,LL m,LL p)
{
    if(n<m)
        return 0;
    if(n==m)
        return 1;
    m=min(n-m,m);
    LL ans=1,cn=1,cm=1;
    for(LL i=0;i<m;++i)
    {
        cn=cn*(n-i)%p;
        cm=cm*(m-i)%p;
    }
    ans=cn*qmod(cm,p-2,p)%p;
    return ans;
}

LL Lucas(LL n,LL m,LL p)
{
    LL ans=1;
    while(n&&m&&ans)
    {
        ans=ans*Comb(n%p,m%p,p)%p;
        n/=p;
        m/=p;
    }
    return ans;
}

int main()
{
    int t,n,m;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        if(n<m)
            swap(n,m);
        printf("%d\n",Lucas(n,m,mod));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值