zoj 3557 How Many Sets II 求Comb(n,m)%p p很大素数 m<=1e4

本文探讨了在给定集合S及其大小n、子集大小m和质数p的情况下,计算满足条件的子集T的数量,并通过模运算进行结果处理。详细介绍了算法实现,包括使用模逆元计算组合数,以及处理不包含连续整数的子集问题。

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

Given a set S = {1, 2, ..., n}, number m and p, your job is to count how many set T satisfies the following condition:

  • T is a subset of S
  • |T| = m
  • T does not contain continuous numbers, that is to say x and x+1 can not both in T

Input

There are multiple cases, each contains 3 integers n ( 1 <= n <= 109 ), m ( 0 <= m <= 104m <= n ) and p ( p is prime, 1 <= p <= 109 ) in one line seperated by a single space, proceed to the end of file.

Output

Output the total number mod p.

Sample Input
5 1 11
5 2 11
Sample Output
5
6

//


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define bignum long long
bignum exgcd(bignum a,bignum b,bignum& x,bignum& y)
{
    if(b==0) return x=1,y=0,a;
    bignum r=exgcd(b,a%b,x,y);
    bignum t=x;
    x=y;
    y=t-(a/b)*y;
    return r;
}
bignum calc(bignum a,bignum b,bignum mod)
{
    bignum x,y;
    bignum r=exgcd(b,mod,x,y);
    x*=a;
    x=(x%mod+mod)%mod;
    return x;
}
//C(n,m)%p   m<=1e4  p是素数
bignum Comb_p(bignum n,bignum m,bignum p)
{
    if(m>n) return 0;//important
    if(m>n/2) m=n-m;
    bignum a=1,b=1;
    bignum nump=0;
    for(bignum i=1;i<=m;i++)
    {
        bignum x=n-i+1,y=i;
        while(x%p==0) x/=p,nump++;
        while(y%p==0) y/=p,nump--;
        a=(a*x)%p;b=(b*y)%p;
    }
    if(nump) return 0;//important
    return calc(a,b,p);
}
//Yi=Xi-Xi-1>=2   Y1>=1  Ym+1>=0  Y1+..Ym+Ym+1=n
int main()
{
    int n,m,p;
    while(scanf("%d%d%d",&n,&m,&p)==3)
    {
        int ans=Comb_p((bignum)n-m+1,(bignum)m,(bignum)p);
        printf("%d\n",ans);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值