D.Brackets(13.7.8)

D.Brackets

This year MK is 5 years old. So he decides to learnsome arithmetic. But he was confused by how towrite the brackets. He has already known that the brackets should match whenwriting them correctly. Such as “()(())” is correct but “())(” is not.

Theproblem is that, if there are N pairs of brackets, how many ways that MK can writethem correctly?           

 

Input

   There areseveral test cases. Each case contains a number N (1 <= N <= 1000)indicating the pairs of brackets.

 

Output

For each case,please output the answer mod 1,000,000,007.

Sample Input

5

7

Sample Output

42

429

刚开始,在即寻找规律,并没有找到,后来在讲题时得知这是卡特兰数的一个实例,在网上寻找了关于卡特兰数的知识,找到了关于卡特兰数的几个公式:

1、C_n = {2n/choose n} - {2n/choose n+1} /quad n/ge 0

这是根据原来的式子推导出来的,大概过程是这样的:C_n = /frac{1}{n+1}{2n/choose n} = {2n/choose n} -  /frac{n}{n+1}{2n/choose n} = {2n/choose n} -  {2n/choose n + 1}

2、C_0 = 1 /quad , /quad C_{n+1}=/frac{2(2n+1)}{n+2}C_n

这个递推式很容易可以从原来的式子中获得

3、/begin{displaymath}C_0 = 1 /quad , /quad C_{n+1}=/sum_{i=0}^{n}C_i/,C_{n-i}/quad n/ge 0/end{displaymath}

4、/begin{displaymath}C_n= /frac 1{n+1} /sum_{i=0}^n {n /choose i}^2/end{displaymath}

5、/begin{displaymath}C_n /sim /frac{4^n}{n^{/frac{3}{2}}/sqrt{/pi}}/end{displaymath}

我使用了看起来较好理解的第三个式子

代码:

#include<iostream>
using namespace std;
const int p=1000000007;
int main(){
	int m;
	long long num[1000]={};
	num[0]=1;
	num[1]=1;
	for(int i=2;i<=1000;i++)
		for(int j=0;j<i;j++){
			num[i]+=num[j]*num[i-1-j]%p;
			num[i]%p;
		}
		while(cin>>m){
		 cout<<num[m]<<endl;
	}
return 0;
}
这个代码,在运行题目所给的运行数据时,完美运行,但是在测试更大的数据时,就不能得到正确的答案了,此时就应该用到数学中取余数的性质,因为,对于过大的数,int是无法存储的,就会出现错误答案,所以应该直接将取模之后的答案存储到num数组,这样才不会出现由于int无法存储大数据而出现答案错误

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值