hdu 1023 ——Train Problem II(卡特兰数+高精度+java)

Train Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7977 Accepted Submission(s): 4278

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.

Author
Ignatius.L

Recommend
We have carefully selected several similar problems for you: 1133 1022 1130 1131 1134

题意:从1~n的n个数依次进栈,问共有多少种出栈方式。

题解:有n个位置,现在任意选定一个数,比如1,那么1可以在1–>n的任意一个位置上。假设1在第k的位置上,显然在1的前面有k-1个数,并且这些数的数值为2–>k,在1后面有n-k个数。用f(k)表示k个数顺序入栈后的出栈顺序,则f(n)就是我们要求的最终答案。而f(n)这个事件又可以分解成1在1–>n这n个位置上出现的n种情况,于是根据加法/乘法原理,易得f(n)是卡特兰数.
但本题还有一个问题,就是会爆long long,要用高精度存。所以我是用了java。
Java使用方法详见收藏夹。

Java代码如下:

import java.util.*;
import java.math.*;

public class Main { 
    public static void main(String[] args) { 
        BigInteger[] f = new BigInteger[100+10];
        f[1] = BigInteger.valueOf(0);
        f[2] = BigInteger.valueOf(1);
        f[3] = BigInteger.valueOf(1);
        for(int i = 3;i <= 103;i++){
            long temp = 4 * i - 6;
            BigInteger T = new BigInteger(String.valueOf(0));
            T = BigInteger.valueOf(temp);
            f[i+1] = f[i].multiply(T);
            T = BigInteger.valueOf(i);
            f[i+1] = f[i+1].divide(T);
        }
        Scanner cin = new Scanner(System.in);
        while(cin.hasNext()){
            int n = cin.nextInt();
            System.out.println(f[n+2]);
        }
    }
}

另注:卡特兰数中f[2]=f[3]=1,f[4]=2,f[5]=5。。。,并不是从一开始的,做本题时要错2位输出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值