N * N的方格,从左上到右下画一条线。一个机器人从左上走到右下,只能向右或向下走。并要求只能在这条线的上面或下面走,不能穿越这条线,有多少种不同的走法?由于方法数量可能很大,只需要输出Mod 10007的结果。
Input输入一个数N(2 <= N <= 10^9)。Output输出走法的数量 Mod 10007。
Sample Input
4
Sample Output
10
PS:本题主要是Lucas定理和卡特兰数,这是Lucas定理的网站,可以看看。https://blog.csdn.net/clove_unique/article/details/54571216。这是卡特兰数的网址:https://www.cnblogs.com/yaoyueduzhen/p/5456490.html。
#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<map>
#include<queue>
#include<set>
#include<cmath>
#include<stack>
#include<string>
const int maxn=1e5+5;
const int mod=10007;
const int inf=1e8;
#define me(a,b) memset(a,b,sizeof(a))
typedef long long ll;
using namespace std;
ll num[maxn];
void inct()
{
num[0]=1;
for(int i=1;i<maxn;i++)
num[i]=num[i-1]*i%mod;
}
ll qpow(ll a,ll b)
{
ll res=1;a%=mod;
while(b)
{
if(b&1)
res=res*a%mod;
a=a*a%mod;
b>>=1;
}
return res;
}
ll C(ll a,ll b)
{
if(a<b)
return 0;
return num[a]*qpow(num[b]*num[a-b],mod-2)%mod;
}
ll Lucas(ll a,ll b)
{
if(!b)
return 1;
return C(a%mod,b%mod)*Lucas(a/mod,b/mod)%mod;
}
int main()
{
ll n;
while(cin>>n)
{
n--;
inct();
cout<<2*(Lucas(2*n,n)-Lucas(2*n,n-1)+mod)%mod<<endl;
}
return 0;
}
不用预处理写法:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N =1e5;
ll n, m,mod=10007,num[N];
ll powmod(ll a,ll b)
{
ll res=1,temp=a;
while(b)
{
if(b&1) res=res*temp%mod;
temp=temp*temp%mod;
b>>=1;
}
return res;
}
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)% mod;
ll b = i % mod;
ans = ans * (a * powmod(b, mod-2) % mod) %mod;
}
return ans;
}
ll lucas(ll a,ll b)
{
if(!b) return 1;
return c(a%mod,b%mod)*lucas(a/mod,b/mod)%mod;
}
int main()
{
while(~scanf("%lld",&n))
{
n--;
printf("%lld\n",2*(lucas(2*n, n)-lucas(2*n, n-1)+mod)%mod);
}
return 0;
}