HDU5894分位置(组合数,lucas,乘法逆元)

题意:

现在 m个考生人需要坐在有n个座位的圆桌上。你需要安排位置,使得任意两个考生之间相距至少k个位置。桌子有编号,考生a和b交换位置视作一种方案,问有多少方案,mod 1e9+7。(0 < m < n < 1e6, 0 < k < 1000)


组合数取模,mod为素数的收,当n,m比较大的时候用到lucas定理去求。


分析转自点击打开链接


假定一个人已经坐在了某个位置,如图所示

那还剩下n-1个位置,而要求相邻两人之间必须隔k个位置,所以m个人就有m*k个位置不能坐

那剩下的位置数为n-1-m*k,由于一个人已经坐好,那我需要从这些剩下的位置中挑选出m-1个位置供剩下的m-1个人就坐

故组合数为C(n-m*k-1,m-1)

然后因为有n个位置,所以第一个人位置的选法就有n种

再考虑此题中每个人都是一样的,即不同方案仅仅是坐的位置序列不同,那上述做法会重复计算m次

比如有3个人,假设他们坐的位置是(2,4,7),那么,(4,2,7),(7,2,4)是重复计算的

故方案数的最终式子应为[C(n-m*k-1,m-1)*n/m]%1000000007

那求解组合数不用想肯定得用lucas定理,毕竟n和m有点大,直接打表已经存不下结果,且会超时

而除法取模部分,考虑到1000000007是质数,且m<1000000007,所以gcd(m,1000000007)=1,故可以直接采取乘法逆元


除法取模就要转化为乘上乘法逆元来做了

乘法逆元:

//扩展欧几里得
void ext_gcd(ll a, ll b, ll&d , ll& x, ll& y){
    if(!b) {d = a; x = 1; y = 0;}
    else{
        ext_gcd(b,a%b,d,y,x);
        y -= x * (a/b);
    }
}
//计算模n下a的逆,如果不存在逆,则返回-1
ll inv(ll a,ll n){
    ll d,x,y;
    ext_gcd(a,n,d,x,y);
    return d == 1?(x+n) % n: -1;
}
求乘法逆元另一个方法是利用欧拉定理。

如果mod为素数,a的逆为pow_mod(a,mod-2,mod).

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
#include<stack>
#include<math.h>
#include<vector>
#include<map>
#include<set>
#include<bitset>
#include<cmath>
#include<complex>
#include<string>
#include<algorithm>
#include<iostream>
#define eps 1e-9
#define PI acos(-1.0)
#define bitnum(a) __builtin_popcount(a)
using namespace std;
const int N = 1000005;
const int M = 100005;
const int inf = 1000000007;
const int mod = 1000000007;
typedef long long ll;
ll fac[N];
void init(){
    fac[0] = 1;
    for(int i=1;i<=N;i++){
        fac[i] = i * fac[i-1] % mod;
    }
}
ll pow_mod(ll a,ll b){
    ll res = 1;
    a = a %mod;
    while(b){
        if(b & 1) res = res * a % mod;
        a = a*a % mod;
        b >>= 1;
    }
    return res;
}
ll C(ll n, ll m){
    if(m>n)
        return 0;
    return  fac[n]*pow_mod(fac[m]*fac[n-m]%mod,mod-2)%mod;
}
ll Lucas(ll n,ll m)
{
    if(m==0)
        return 1;
    return C(n%mod,m%mod)*Lucas(n/mod,m/mod)%mod;
}
//扩展欧几里得
void ext_gcd(ll a, ll b, ll&d , ll& x, ll& y){
    if(!b) {d = a; x = 1; y = 0;}
    else{
        ext_gcd(b,a%b,d,y,x);
        y -= x * (a/b);
    }
}
//计算模n下a的逆,如果不存在逆,则返回-1
ll inv(ll a,ll n){
    ll d,x,y;
    ext_gcd(a,n,d,x,y);
    return d == 1?(x+n) % n: -1;
}
int main(){
    int T;
    init();
    scanf("%d",&T);
    while(T--){
        ll n,m,k;
        scanf("%lld%lld%lld",&n,&m,&k);
        printf("%lld\n",(Lucas(n-1-m*k,m-1)*n%mod)*inv(m,mod)%mod);
       // printf("%lld\n",(Lucas(n-1-m*k,m-1)*n%mod)*pow_mod(m,mod-2)%mod);

    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值