ZOJ 3557-How Many Sets II(Lucas定理+插板法求组合数)

6 篇文章 0 订阅

题目地址:ZOJ 3557
题意:给一个集合,一共n个元素,从中选取m个元素,满足选出的元素中没有相邻的元素,一共有多少种选法(结果对p取模1 <= p <= 10^9)
思路:用插板法求出组合数。既然是从n个数中选择m个数,那么剩下的数为n-m,那么可以产生n-m+1个空,这道题就变成了把m个数插到这n-m+1个空中有多少种方法,即C(n-m+1,m)%p。然后就Lucas定理上去乱搞。因为这道题的p较大,所以不能预处理。

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <set>
#include <queue>
#include <stack>
#include <map>
#include <bitset>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
typedef long long LL;
const int inf=0x3f3f3f3f;
const double pi= acos(-1.0);
const double esp=1e-6;
using namespace std;
LL n,m,p;
LL modxp(LL a,LL b)
{
    LL res=1;
    while(b>0){
        if(b&1)
            res=res*a%p;
        b=b>>1;
        a=a*a%p;
    }
    return res;
}
LL C(LL n,LL m)
{
    if(m>n) return 0;
    if(m==n) return 1;
    LL ans=1;
    for(int i=1;i<=m;i++){
        LL a=(n+i-m)%p;
        LL b=i%p;
        ans=ans*(a*modxp(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);
}
int main()
{
    while(~scanf("%lld %lld %lld",&n,&m,&p)){
        printf("%lld\n",Lucas(n-m+1,m)%p);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rocky0429

一块也是爱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值