zoj 3557 How Many Sets II 求Comb(n,m)%p p很大素數 m

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章