zoj 3557 lucas定理

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 
#include 
#include 
#include 
#include 
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;
}

你可能感兴趣的:(数学基础)