51NOD 1120 机器人走方格 V3(卢卡斯定理 + 非降路径)

来源:互联网 发布:大数据时代 英文版 txt 编辑:程序博客网 时间:2024/04/30 14:31

传送门

N * N的方格,从左上到右下画一条线。一个机器人从左上走到右下,只能向右或向下走。并要求只能在这条线的上面或下面走,不能穿越这条线,有多少种不同的走法?由于方法数量可能很大,只需要输出Mod 10007的结果。
Input
输入一个数N(2 <= N <= 10^9)。
Output
输出走法的数量 Mod 10007。
Input示例
4
Output示例
10
解题思路:
从左上做到右下只能向右护着向下走,就是相当于从左下走到右上的一条非降路径,然后中间加了一些障碍,其实就是从(1,1) 走到 (n,n) 点不能碰到对角线的非降路径。直接套公式:
2nC(2(n1),n1)
因为 n 太大了,而取模的数不是很大,很容易想到 Lucas 定理。然后就是敲代码了,都是套路,求的是 还需要求一下 MOD 关于 n 的逆元,但是没有逆元的情况怎么求呢 好像没有这样的数据。

My Code

/**2016 - 08 - 05 下午Author: ITAKMotto:今日的我要超越昨日的我,明日的我要胜过今日的我,以创作出更好的代码为目标,不断地超越自己。**/#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#include <cmath>#include <vector>#include <queue>#include <algorithm>#include <set>using namespace std;typedef long long LL;typedef unsigned long long ULL;const int INF = 1e9+5;const int MAXN = 1e6+5;const LL MOD = 1e4+7;const double eps = 1e-7;const double PI = acos(-1);using namespace std;LL quick_mod(LL a, LL b, LL c){    LL ans = 1;    while(b)    {        if(b & 1)            ans = (ans*a)%c;        b>>=1;        a = (a*a)%c;    }    return ans;}LL fac[MAXN];void Get_Fac(LL m)///m!{    fac[0] = 1;    for(int i=1; i<=m; i++)        fac[i] = (fac[i-1]*i) % m;}LL Lucas(LL n, LL m, LL p){    LL ans = 1;    while(n && m)    {        LL a = n % p;        LL b = m % p;        if(a < b)            return 0;        ans = ( (ans*fac[a]%p) * (quick_mod(fac[b]*fac[a-b]%p,p-2,p)) ) % p;        n /= p;        m /= p;    }    return ans;}void Exgcd(LL a, LL b, LL &x, LL &y){    if(b == 0)    {        x = 1;        y = 0;        return;    }    LL x1, y1;    Exgcd(b, a%b, x1 ,y1);    x = y1;    y = x1 - (a/b)*y1;}int main(){    Get_Fac(MOD);    LL n;    while(cin>>n)    {        LL x, y;        Exgcd(n, MOD, x, y);        x = (x%MOD+MOD)%MOD;        x<<=1LL;        LL ans = Lucas(2*n-2, n-1, MOD);        ans = (ans*x)%MOD;        cout<<ans<<endl;    }    return 0;}
0 0