Train Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7252 Accepted Submission(s): 3902
Total Submission(s): 7252 Accepted Submission(s): 3902
Problem Description
As we all know the Train Problem I, the boss of the Ignatius Train Station want to know if all the trains come in strict-increasing order, how many orders that all the trains can get out of the railway.
Input
The input contains several test cases. Each test cases consists of a number N(1<=N<=100). The input is terminated by the end of file.
Output
For each test case, you should output how many ways that all the trains can get out of the railway.
Sample Input
1 2 3 10
Sample Output
1 2 5 16796HintThe result will be very large, so you may not process it by 32-bit integers.解题思路:对于给定的n个数,依次入栈,其可能的出栈序列个数是一个Catalan Number.Catalan 数列的递推公式是:![]()
![]()
渐进增长为:![]()
![]()
可知当i比较大时,Cn将是一个很大的数,不仅32-bit不够存储,64-bit也不够,因此考虑高精度乘除法。关于Catalan Number,参考Wikipedia: Catalan number# include <iostream> # include <cstdio> # include <iomanip> # include <algorithm> using namespace std; string calcMuly(int a, string b) { string res; int len = b.length(); int carry = 0; for(int i = len - 1; i >= 0; --i) { int tmp = (b[i] - '0') * a + carry; res.push_back(tmp % 10 + '0'); carry = tmp / 10; } if(carry){ while(carry){ res.push_back(carry % 10 + '0'); carry /= 10; } } reverse(res.begin(), res.end()); return res; } string calcDivision(string a, int b) { string res; int len = a.size(); int r = 0; for(int i = 0; i < len; ++i) { int tmp = r * 10 + (a[i] - '0'); res.push_back(tmp / b + '0'); r = tmp % b; } int i; for(i = 0; res[i] == '0'; ++i) ; return res.substr(i, len - i + 1); } int main() { int n; vector<string> catalan(101); catalan[0] = "1"; for(int i = 1; i <= 100; ++i) { catalan[i] = calcDivision(calcMuly(4 * i - 2, catalan[i - 1]), (i + 1)); } while(cin >> n) { cout << catalan[n] << endl; } }