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、
这是根据原来的式子推导出来的,大概过程是这样的:
2、
这个递推式很容易可以从原来的式子中获得
3、
4、
5、
我使用了看起来较好理解的第三个式子
代码:
#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无法存储大数据而出现答案错误