HDU 1023 Traning Problem (2) 高精度卡特兰数

时间:2023-03-09 04:25:13
HDU 1023 Traning Problem (2) 高精度卡特兰数
Time Limit: 1000MS   Memory Limit: 32768KB   64bit IO Format: %I64d & %I64u

Submit Status

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.
         

Source

求高精度的卡特兰数。

1.java代码,套公式就可以了。

import java.io.*;
import java.util.*;
import java.math.BigInteger; public class Main
{
public static void main(String args[])
{
BigInteger[] a = new BigInteger[101];
a[0] = BigInteger.ZERO;
a[1] = BigInteger.valueOf(1);
for(int i = 2; i <= 100; ++i)
a[i] = a[i - 1].multiply(BigInteger.valueOf(4 * i - 2)).divide(BigInteger.valueOf(i+1));
Scanner in = new Scanner(System.in);
int n;
while(in.hasNext())
{
n = in.nextInt();
System.out.println(a[n]);
}
}
}

2.C++代码,kuangbin模板

//h( n ) = ( ( 4*n-2 )/( n+1 )*h( n-1 ) );

#include<stdio.h>

//*******************************
//打表卡特兰数
//第 n个 卡特兰数存在a[n]中,a[n][0]表示长度;
//注意数是倒着存的,个位是 a[n][1] 输出时注意倒过来。
//*********************************
int a[][];
void ktl()
{
int i,j,yu,len;
a[][]=;
a[][]=;
a[][]=;
a[][]=;
len=;
for(i=;i<;i++)
{
yu=;
for(j=;j<=len;j++)
{
int t=(a[i-][j])*(*i-)+yu;
yu=t/;
a[i][j]=t%;
}
while(yu)
{
a[i][++len]=yu%;
yu/=;
}
for(j=len;j>=;j--)
{
int t=a[i][j]+yu*;
a[i][j]=t/(i+);
yu = t%(i+);
}
while(!a[i][len])
{
len--;
}
a[i][]=len;
} }
int main()
{
ktl();
int n;
while(scanf("%d",&n)!=EOF)
{
for(int i=a[n][];i>;i--)
{
printf("%d",a[n][i]);
}
puts("");
}
return ;
}

3.C++代码

#include <iostream>
#include <stdio.h>
#include <cmath>
using namespace std; int a[][]; //大数卡特兰数
int b[]; //卡特兰数的长度 void catalan() //求卡特兰数
{
int i, j, len, carry, temp;
a[][] = b[] = ;
len = ;
for(i = ; i <= ; i++)
{
for(j = ; j < len; j++) //乘法
a[i][j] = a[i-][j]*(*(i-)+);
carry = ;
for(j = ; j < len; j++) //处理相乘结果
{
temp = a[i][j] + carry;
a[i][j] = temp % ;
carry = temp / ;
}
while(carry) //进位处理
{
a[i][len++] = carry % ;
carry /= ;
}
carry = ;
for(j = len-; j >= ; j--) //除法
{
temp = carry* + a[i][j];
a[i][j] = temp/(i+);
carry = temp%(i+);
}
while(!a[i][len-]) //高位零处理
len --;
b[i] = len;
}
} int main()
{
int i, n;
catalan();
while(scanf("%d", &n) != EOF)
{
for(i = b[n]-; i>=; i--)
{
printf("%d", a[n][i]);
}
printf("\n");
} return ;
}