Train Problem II

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
答案:

注:
卡特兰数:卡特兰数又称卡塔兰数,是组合数学中一个常出现在各种计数问题中出现的数列。由以比利时的数学家欧仁·查理·卡塔兰 (1814–1894)命名。
原理:
  令h(1)=1,h(0)=1,catalan数满足递归式:   h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)h(0) (其中n>=2)   另类递归式:   h(n)=((4*n-2)/(n+1))*h(n-1);   该递推关系的解为:   h(n)=C(2n,n)/(n+1) (n=1,2,3,...)
卡特兰数的应用:实质上都是递归等式的应用


#include <stdio.h>
#include <string>
#include <cmath>
char string[10000];
char out[10000];
void calculate(long n)
{
 if (n == 1)
 {
  string[0] = '1';
  out[0] = '1';
 }
 else
 {
  long v = (4*n-2);
  long d = (n+1);
  long space = 0;
  long w, i, s, le, k;
  if (d < 10)
   space = 1;
  else if (d < 100)
   space = 2;
  else
   space = 3;
  calculate(n-1);
  // multiplication
  le = strlen(string);
  s = 0;
  for (i = 0; i < le; ++i)
  {
   w = v*(string[i]-'0')+s;
   string[i] = w%10 + '0';
   s = w/10;
  }
  while (s > 0)
  {
   string[i++] = s%10 + '0';
   s = s/10;
  }
  // division
  memset(out, 0, sizeof(out));
  le = strlen(string);
  s = 0;
  w = 0;
  k = 0;
  for (i = 0; i < space; ++i)
   w += pow(10, space-i-1)*(string[le-i-1]-'0');
  for (i = space; i < le; ++i)
  {
   if (k != 0 || w/d != 0)
    out[k++] = w/d + '0';
 
   s = w%d;
   w = string[le-i-1]-'0'+10*s;
  }
  out[k++] = w/d + '0';
  // exchange
  memset(string, 0, sizeof(string));
  for (k = strlen(out)-1, i = 0; k >= 0; --k)
  {
   string[i++] = out[k];
  }
 }
}
int main(int argc, char* argv[])
{
 long n;
 while (scanf("%d", &n)!=EOF && n)
 {
  memset(string, 0, sizeof(string));
  calculate(n);
  printf("%s/n", out);
 }
 
 return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值