20130707 【南华大学 ACM】 新生赛第一场 【D.Brackets】

时间:2023-01-09 09:29:41

D.Brackets

This year MK is 5 years old. So he decides to learnsomearithmetic. 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》老实说,我第一次只得到求解公式:h(n)=1/(n+1)*C(2n,n);

2》然后就,求不出来了。

3》后来才知道,这就是卡特兰数(Catalan)

【卡特兰数.百度百科:http://baike.baidu.com/view/2499752.htm】


由 卡特兰数 资料,知:Catalan数满足:
1)递归式:              h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)h(0) (其中n>=2)

2)另类递推式:       h(n)=h(n-1)*(4*n-2)/(n+1);                                 (其中n>=1)

3)递推关系的解为:h(n)=C(2n,n)/(n+1)=C(2n,n)-C(2n,n+1)          (n=0,1,2,...)

4)从第0项开始,卡特兰数为:
1, 1, 2,5,14,42,132,429,1430,4862,16796,58786,208012,742900, 2674440,9694845,35357670,129644790,477638700,1767263190,6564120420,24466267020,91482563640,343059613650,1289904147324,4861946401452, ...

5)然后,为了解决此题,只能选用公式1)。(为什么呢?你猜!!)


--------------------------------------------------------------------------------
代码:

#include<iostream>
using namespace std;
const long MOD=1000000007;
int main()
{
	int n,i,j,m;
	long long c[2000];
	c[0]=c[1]=1;
	while( cin>>n )
	{
		for(m=2; m<=n ;m++)
		{
			for(c[m]=0,i=0,j=m-1;i<=m-1;i++,j--)
				c[m]+=(c[i]*c[j])%MOD;
			c[m]%=MOD;
		}
		cout<<c[n]%MOD<<endl;
	}
	return 0;
}