码迷,mamicode.com
首页 > 其他好文 > 详细

zoj 3557 lucas定理

时间:2015-02-07 16:01:15      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:组合数

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

zoj 3557 lucas定理

标签:组合数

原文地址:http://blog.csdn.net/liusuangeng/article/details/43603387

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!