51 NOD 1119 机器人走方格 V2(Lucas)

题目链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1119


基准时间限制:1 秒 空间限制:131072 KB 分值: 10  难度:2级算法题
 收藏
 关注
M * N的方格,一个机器人从左上走到右下,只能向右或向下走。有多少种不同的走法?由于方法数量可能很大,只需要输出Mod 10^9 + 7的结果。
Input
第1行,2个数M,N,中间用空格隔开。(2 <= m,n <= 1000000)
Output
输出走法的数量 Mod 10^9 + 7。
Input示例
2 3
Output示例
3


解析:求C(m+n-2, n - 1), 运用Lucas定理求


快速幂:

#include<bits/stdc++.h>
#define N 10009
using namespace std;
typedef long long LL;

LL q_mod(LL a, LL b, LL p)
{
    LL ans = 1;
    while(b)
    {
        if(b & 1) ans = ans * a % p;
        b >>= 1;
        a = a * a % p;
    }
    return ans % p;
}

LL c_mn(LL n, LL m, LL p)
{
    if(n < m) return 0;
    if(m == n) return 1;
    LL ca, cb;
    ca = cb = 1;
    for(int i = 0; i < m; i++)
    {
        ca = ca * (n - i) % p;
        cb = cb * (m - i) % p;
    }
    // ca / cb
    return ca * q_mod(cb, p - 2, p) % p;
}

LL Lucas(int n, int m, int p)
{
    LL ans = 1;
    while(m && n && ans)
    {
        ans = ans * c_mn(n % p, m % p, p) % p;
        n /= p;
        m /= p;
    }
    return ans;
}


int main()
{
    int m, n;
    int p = 1e9 + 7;
    cin >> m >> n;
    LL ans = Lucas(m + n - 2, n - 1, p);
    cout << ans << endl;
    return 0;
}



扩展欧几里得:

#include<bits/stdc++.h>
#define N 10009
using namespace std;
typedef long long LL;

void e_gcd(LL a, LL b, LL &x, LL &y)
{
    if(b == 0)
    {
        x = 1; y = 0;
        return ;
    }
    e_gcd(b, a % b, x, y);
    LL t = x; x = y;
    y = t - a / b * y;
}

LL c_mn(LL n, LL m, LL p)
{
    if(n < m) return 0;
    if(m == n) return 1;
    LL ca, cb, x, y;
    ca = cb = 1;
    for(int i = 0; i < m; i++)
    {
        ca = ca * (n - i) % p;
        cb = cb * (m - i) % p;
    }
    // ca / cb
    e_gcd(cb, p, x, y);
    x = ((x % p) + p) % p;
    return ca * x % p;
}

LL Lucas(int n, int m, int p)
{
    LL ans = 1;
    while(m && n && ans)
    {
        ans = ans * c_mn(n % p, m % p, p) % p;
        n /= p;
        m /= p;
    }
    return ans;
}


int main()
{
    int m, n;
    int p = 1e9 + 7;
    cin >> m >> n;
    LL ans = Lucas(m + n - 2, n - 1, p);
    cout << ans << endl;
    return 0;
}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值