码迷,mamicode.com
首页 > 其他好文 > 详细

B - Game of Connections(卡特兰数)

时间:2017-07-22 12:08:43      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:different   logs   which   not   lin   using   计算   解法   --   

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? 

InputEach 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. 
OutputFor 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

解法:
卡特兰数的计算公式:a[n] = a[n-1]*(4*n-1)/n+1;
主要的问题在于大数的处理上
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<cstring>
 5 
 6 using namespace std;
 7 
 8 const int N = 10000;
 9 int a[101][101];
10 
11 void cheng( int temp ,int i)
12 {
13     int temp1 = 0;
14     for(int j = 100;j >=  0;j--)
15     {
16         temp1 = a[i-1][j] * temp + temp1;
17         a[i][j] = temp1 % N;
18         temp1  = temp1 / N;
19     }
20     
21 }
22 
23 void chu (int temp,int i)
24 {
25     int temp1 = 0;
26     for(int j = 0;j  <= 100;j++)
27     {
28         temp1 = temp1*N + a[i][j];
29         a[i][j] = temp1 / temp;
30         temp1 = temp1 % temp;
31     }
32     
33 }
34 
35 
36 void DP()
37 {
38     memset(a,0,sizeof(a));
39     a[1][100] = 1;
40     for(int i = 2;i <= 100;i++)
41     {
42         int temp;
43         temp = 4*i-2;
44         cheng(temp,i);
45         temp = i + 1;
46         chu(temp,i);
47     }    
48     
49 }
50 
51 int main ()
52 {
53     DP();
54     int t;
55     while(cin>>t)
56     {
57         if(t == -1)
58             break;
59         int temp;
60         for(int i = 0;i <=100;i++)
61             if( a[t][i] )
62                 {
63                     temp = i;
64                     break;
65                 }
66         printf("%d",a[t][temp]);
67         for(int i = temp+1;i <= 100;i++){
68             printf("%04d",a[t][i]);
69         }
70         cout<<endl;
71    }
72 }

 

B - Game of Connections(卡特兰数)

标签:different   logs   which   not   lin   using   计算   解法   --   

原文地址:http://www.cnblogs.com/a2985812043/p/7220546.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!