DP? HDU - 3944 Lucas定理+费马小定理

肯定是尽量走1,因为最左边的1和最右边的1相同,所以我们考虑一边就行了,就考虑(m < k/2)

最后我们推出来的公式为:
C(n+1,m)+(n-m)

因为C(n+1,m)很大。

要用到Lucas定理
什么是Lusac(卢卡斯)定理?
Lucas定理是用来求 c(n,m) mod p,p为素数的值。
对于C(n, m) mod p。这里的n,m,p(p为素数)都很大的情况。就不能再用C(n, m) = C(n - 1,m) + C(n - 1, m - 1)的公式递推了。

参考http://www.cnblogs.com/vongang/archive/2012/12/02/2798138.html
For non-negative integers m and n and a prime p, the following congruence relation holds:

where

这里写图片描述
and
这里写图片描述

are the base p expansions of m and n respectively.
这里写图片描述

对于单独的C(ni, mi) mod p,已知C(n, m) mod p = n!/(m!(n - m)!) mod p。显然除法取模,这里要用到m!(n-m)!的逆元。

根据费马小定理:
http://blog.csdn.net/ac__y/article/details/9248023

已知(a, p) = 1,则 ap-1 ≡ 1 (mod p), 所以 a*ap-2 ≡ 1 (mod p)。

也就是 (m!(n-m)!)的逆元为 (m!(n-m)!)p-2 ;

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>

using namespace std;

#define LL long long
LL ni(LL b,LL n,LL p)
{
    LL x=1;
    while(n)
    {
        if(n&1) x=(x*b)%p;
        b=(b*b)%p;
        n>>=1;
    }
    return x;
}
LL c(LL n,LL m,LL p)
{
    if(m>n) return 0;
    else if(n==m) return 1;
    if(m>n/2) m=n-m;
    LL a=1,b=1;
    for(int i=0;i<m;i++)
    {
        a=(a*(n-i))%p;
        b=(b*(i+1))%p;
    }
    return (a*ni(b,p-2,p))%p;
}
LL Lucas(LL n,LL m,LL p)
{
    LL ans=1;
    while(n&&m&&p)
    {
        ans=(ans*c(n%p,m%p,p))%p;
        n=n/p;
        m=m/p;
    }
    return ans;
}
int main()
{
    LL n,m,p;
    int case1=1;
    while(scanf("%I64d %I64d %I64d",&n,&m,&p)!=EOF)
    {
        if(m>n/2) m=n-m;
        printf("Case #%d: %I64d\n",case1++,((n-m)+Lucas(n+1,m,p))%p);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值