HDU 5698 (数学 lucas)

瞬间移动

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 489    Accepted Submission(s): 274


Problem Description
有一个无限大的矩形,初始时你在左上角(即第一行第一列),每次你都可以选择一个右下方格子,并瞬移过去(如从下图中的红色格子能直接瞬移到蓝色格子),求到第 n行第 m列的格子有几种方案,答案对 1000000007取模。

![http://acm.hdu.edu.cn/data/images/C702-1003-1.jpg](http://acm.hdu.edu.cn/data/images/C702-1003-1.jpg)
 

Input
多组测试数据。

两个整数 n,m(2n,m100000)
 

Output
一个整数表示答案
 

Sample Input

4 5
 

Sample Output

10
 


显然某一个坐标的方案数就是他下方加右方,把图转45°看就是一个杨辉三角,

然后就是对坐标进行组合数取模,答案是C(n+m-4,n-2).

#include 
#include 
#include 

using namespace std;
typedef long long LL;

LL n,m,p;

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

LL C(LL n, LL m)
{
    if(m > n) return 0;
    LL ans = 1;
    for(int i=1; i<=m; i++)
    {
        LL a = (n + i - m) % p;
        LL b = i % p;
        ans = ans * (a * quick_mod(b, p-2) % p) % p;
    }
    return ans;
}

LL Lucas(LL n, LL m)
{
    if(m == 0) return 1;
    return C(n % p, m % p) * Lucas(n / p, m / p) % p;
}

int main()
{
    p = 1000000007;
    while(scanf("%I64d%I64d", &n, &m) == 2)
    {
        if (n == 1 || m == 1) {
            printf ("0\n");
            continue;
        }
        printf("%I64d\n", Lucas (n+m-4, n-2));
    }
    return 0;
}


你可能感兴趣的:(数论/推导)