zoj 3557 lucas定理

本文介绍了一种算法,用于解决从给定集合中找出所有符合条件的子集数量的问题,这些子集的元素个数固定且不含连续数字。通过转换为组合问题并利用Lucas定理求解模意义下的组合数。

摘要生成于 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 <= 104, m <= 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

分析:从n个数里面取出m个来,并且不能有相邻数,等价于
不选n-m个数,那么就得到n-m+1个空吧。
这样原来要求的组合数就变成了将m个数插入n-m+1个空的方法数:
C(n-m+1,m)即可
运用lucas定理: lucas(n,m,p)=C(n%p,m%p,p)*lucas(n/p,m/p,p);

#include <iostream>
#include <stdio.h>
#include <string>
#include <string.h>
#include <algorithm>
using namespace std;
typedef long long ll;

ll quick_mod(ll a,ll b,ll mod)
{
    ll ans=1;
    while(b)
    {
       if(b&1)ans=ans*a%mod;
       b/=2;
       a=a*a%mod;
    }
    return ans;
}

ll C(ll n,ll m,ll p)
{
   ll ans=1;
   for(int i=1;i<=m;i++)
   {
     ans=ans*((n-m+i)%p)%p;
     ans=ans*quick_mod(i,p-2,p)%p;
   }
   return ans;
}

ll lucas(ll n,ll m,ll p)
{
  if(m==0)return 1;
  return (C(n%p,m%p,p)%p*(lucas(n/p,m/p,p)%p))%p;
}


int main()
{
    ll n,m,p;
    while(scanf("%lld%lld%lld",&n,&m,&p)!=EOF)
    {
        printf("%lld\n",lucas(n-m+1,m,p));
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值