首页 > 代码库 > 卡特兰数
卡特兰数
A - 卡特兰数
Time Limit:1000MS Memory Limit:30000KB 64bit IO Format:%I64d & %I64uDescription
This is a small but ancient game. You are supposed to write down the numbers 1, 2, 3, . . . , 2n - 1, 2n consecutively in clockwise order on the ground to form a circle, and then, to draw some straight line segments to connect them into number pairs. Every number must be connected to exactly one another.
And, no two segments are allowed to intersect.
It‘s still a simple game, isn‘t it? But after you‘ve written down the 2n numbers, can you tell me in how many different ways can you connect the numbers into pairs? Life is harder, right?
And, no two segments are allowed to intersect.
It‘s still a simple game, isn‘t it? But after you‘ve written down the 2n numbers, can you tell me in how many different ways can you connect the numbers into pairs? Life is harder, right?
Input
Each line of the input file will be a single positive number n, except the last line, which is a number -1.
You may assume that 1 <= n <= 100.
You may assume that 1 <= n <= 100.
Output
For each n, print in a single line the number of ways to connect the 2n numbers into pairs.
Sample Input
2 3 -1
Sample Output
2 5
卡特兰数的计算,大数处理,包括大数乘和大数除的模拟;
#include<stdio.h> #include<string.h> int c[110][110],len[110]; void catalan(){ int a[110][110],b[110][110]; memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); memset(c,0,sizeof(c)); c[1][0] = 1; int k; len[1] = 1; for(int i = 2;i<=100;i++){ int j,s=0; k=0; for(int j = 0;s!=0||j<len[i-1];j++){ a[i][k++] = (c[i-1][j]*(4*i-2)+s)%10; s = (c[i-1][j]*(4*i-2)+s)/10; } int cha = 0,m=0; for(int jj = k-1; jj>=0;jj--){ b[i][m++] = (a[i][jj] + cha *10) /(i+1); cha = (a[i][jj]+cha*10) % (i+1); } int mm = 0,ss; for( ss = 0;b[i][ss]==0;ss++); for(int j=m-1;j>=ss;j--){ c[i][mm++] = b[i][j]; } len[i] = mm; } } int main(){ int n; catalan(); while(scanf("%d",&n),n!=-1){ for(int i = len[n]-1;i>=0;i--){ printf("%d",c[n][i]); } printf("\n"); } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。