题意:询问有多少种进站出站的顺序。
经典卡特兰。我对卡特兰目前的认识就是有n个1和n个-1,组成一个为2n的数列的方式有多少种。这就跟火车进站出站类似,
至于具体的卡特兰数的介绍,百度解释的很详细。
代码1(c语言):
/* h(n) = h(n-1)*(4*n-2)/(n+1); */ #include <stdio.h> #include <string.h> #define M 110 int s[M][M] = {0}, b[M]; void init(){ s[1][0] = 1; b[1] = 1; int i, j, k = 1; for(i = 2; i < 105; i ++){ for(j = 0; j < k; j ++) s[i][j] = s[i-1][j]*(4*i-2); int z = 0; for(j = 0; j < k; j ++){ s[i][j] += z; z = s[i][j]/10; s[i][j]%=10; } while(z){ s[i][k++] = z%10; z /= 10; } z = 0; for(j = k-1; j >= 0; j --){ s[i][j] += z*10; z = s[i][j]%(i+1); s[i][j]/=(i+1); } while(s[i][k-1] == 0) --k; b[i] = k; } } int main(){ init(); int n, i; while(~scanf("%d", &n)){ for(i = b[n]-1; i >= 0; i --) printf("%d", s[n][i]); puts(""); } return 0; }代码2(java):
/* * hdoj 1023 train problem II */ import java.util.Scanner; import java.math.*; public class Main{ public static void main(String[] args){ Scanner cin = new Scanner(System.in); BigInteger[] s = new BigInteger[110]; s[1] = new BigInteger("1"); int i; for(i = 2; i < 110; i ++){ s[i] = new BigInteger("1"); int temp = i*4-2, j = 0; BigInteger c = new BigInteger(((Integer)temp).toString()); s[i] = s[i].multiply(s[i-1]); s[i] = s[i].multiply(c); int b = i+1; c = new BigInteger(((Integer)b).toString()); //System.out.println(c); s[i] = s[i].divide(c); } int n; while(cin.hasNext()){ n = cin.nextInt(); System.out.println(s[n]); } } }
hdoj 1023 Train Problem II 【卡特兰】+【高精度】
原文地址:http://blog.csdn.net/shengweisong/article/details/39213861