-
Notifications
You must be signed in to change notification settings - Fork 2
/
10303.cpp
executable file
·103 lines (88 loc) · 2.72 KB
/
10303.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// In fact, the number we calculate here is Catalan Number.
// You can find some information about it.
// C(n) = ( 4n-2 ) / ( n + 1 ) * C( n - 1 )
#include <iostream>
#include <iomanip>
using namespace std ;
int main()
{
long long digit15 = 10000000 ;
digit15 *= digit15 ;
digit15 *= 10 ;
int number_longint[ 1001 ] = { 0 } ;
number_longint[ 1 ] = 1 ;
//Here we use large number.
//For int n, the Catalan number of n is from Catalan_number[ n ][ 1 ]
//to Catalan_number[ n ][ number_longint[ n ] ]
long long *Catalan_number[ 1001 ] ;
Catalan_number[ 1 ] = new long long [ number_longint[ 1 ] + 1 ] ;
Catalan_number[ 1 ][ 1 ] = 1 ;
for( int i = 2 ; i <= 1000 ; i++ )
{
//Calculate the long long int numbers we need.
if( Catalan_number[ i - 1 ][ number_longint[ i - 1 ] ] >= digit15 / 4000 )
{
number_longint[ i ] = number_longint[ i - 1 ] + 1 ;
}
else
{
number_longint[ i ] = number_longint[ i - 1 ] ;
}
//Allocate the space of Catalan_number[ i ]
Catalan_number[ i ] = new long long [ number_longint[ i ] + 1 ] ;
Catalan_number[ i ][ 0 ] = 0 ;
// First, we calculate (4i-2) * C(i-1)
for( int j = 1 ; j <= number_longint[ i - 1 ] ; j++ )
{
//Check if there is carry.
if( Catalan_number[ i ][ j - 1 ] >= digit15 )
{
Catalan_number[ i ][ j ] = Catalan_number[ i ][ j - 1 ] / digit15 ;
Catalan_number[ i ][ j - 1 ] = Catalan_number[ i ][ j - 1 ] % digit15 ;
}
else
{
Catalan_number[ i ][ j ] = 0 ;
}
// Use the recursion formula to calculate Catalan number.
Catalan_number[ i ][ j ] += Catalan_number[ i - 1 ][ j ] * ( 4 * i - 2 ) ;
}
for( int j = number_longint[ i - 1 ] + 1 ; j <= number_longint[ i ] ; j++ )
{
//Check if there is carry.
if( Catalan_number[ i ][ j - 1 ] >= digit15 )
{
Catalan_number[ i ][ j ] = Catalan_number[ i ][ j - 1 ] / digit15 ;
Catalan_number[ i ][ j - 1 ] = Catalan_number[ i ][ j - 1 ] % digit15 ;
}
else
{
Catalan_number[ i ][ j ] = 0 ;
}
}
// Second, we divide "(4i-2) * C(i-1)" by (i+1)
for( int j = number_longint[ i ] ; j > 1 ; j-- )
{
Catalan_number[ i ][ j - 1 ] += ( Catalan_number[ i ][ j ] % ( i + 1 ) )
* digit15 ;
Catalan_number[ i ][ j ] = Catalan_number[ i ][ j ] / ( i + 1 ) ;
}
Catalan_number[ i ][ 1 ] = Catalan_number[ i ][ 1 ] / ( i + 1 ) ;
}
int input ;
while( cin >> input )
{
int i = number_longint[ input ] ;
while( Catalan_number[ input ][ i ] == 0 )
{
i-- ;
}
cout << Catalan_number[ input ][ i ] ;
for( i = i - 1 ; i >= 1 ; i-- )
{
cout << setw( 15 ) << setfill('0') << Catalan_number[ input ][ i ] ;
}
cout << endl ;
}
return 0 ;
}