hdoj--1023 Train Problem II (高精度乘除法)

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


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 16796
Hint
The 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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值