现在的位置: 首页 > 综合 > 正文

有关卡特兰数

2017年11月21日 ⁄ 综合 ⁄ 共 1255字 ⁄ 字号 评论关闭

题意:一行格子,每次给n,说明可以走n2*n步,但是最后都要回到原点。大体是这个意思吧。。。。

然后自己先模拟一下,本质就跟卡特兰数一样,就是走方格的不同路径数的模型。然后就写啦。。。要求逆元,因为取模运算没有除法性质,所以要变成求逆元的模。

卡特兰的公式很多,用的是递推式,C(n+1)=(4*n+2)/(n+2) *Cn。

然后不知道为什么方法一样,我是擦边过的,人家就跑了五百,还有一百的。。。

#include <stdio.h>
#include <iostream>
using namespace std;
const int N = 1000001;
const long long MOD = (long long)1E9 + 7LL;
long long g;

void extGCD(long long a,long long b,long long &x,long long &y)
{
	if(b == 0)
	{
		x = 1, y = 0;
		g = a;
		return ;
	}
	extGCD(b, a % b, y, x);
	y -= a / b * x;
}

long long modReverse(long long a, long long n)
{
	long long x, y;
	extGCD(a, n, x, y);
	return (x + n) % n;
}

long long Catalan[N];	//0 1 2 3 4  5  6   7   8    9    10    11    12
void genCatalan()	//1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012
{
	Catalan[0] = Catalan[1] = 1LL;
	for (int i = 2; i < N; i++)
	{
		long long tmp = modReverse(i+1LL, MOD);
		Catalan[i] = Catalan[i - 1] * ((i<<2) - 2) % MOD * tmp % MOD;
	}
}
template<class T>
inline char read(T &n){
    T x = 0, tmp = 1; char c = getchar();
    while((c < '0' | c > '9') && c != '-' && c != EOF) c = getchar();
    if(c == '-') c = getchar(), tmp = -1;
    while(c >= '0' && c <= '9') x *= 10, x += (c - '0'),c = getchar();
    n = x*tmp;
    return c;
}
template <class T>
inline void write(T n) {
    if(n < 0) {
        putchar('-');
        n = -n;
    }
    int len = 0,data[20];
    while(n) {
        data[len++] = n%10;
        n /= 10;
    }
    if(!len) data[len++] = 0;
    while(len--) putchar(data[len]+48);
}
int main()
{
	genCatalan();
	int T, num;
	//scanf("%d", &T);
	read(T);
	for (int t = 1; t <= T; t++)
	{
		//scanf("%d", &num);
		read(num);
		printf("%I64d\n", Catalan[num]);
	}
	return 0;
}

抱歉!评论已关闭.