Count the Trees 典型卡特兰数

                      

            Count the Trees

题目分析:给你n个分别标为1,2,...,n的节点,问可以构成多少棵而叉树。

分析:首先考虑n个节点是相同的。任选一个节点做跟节点,那么剩下的n-1个节点构成跟节点的左子树和又子数。

h[n] = h[0] * h[n-1] + h[1] * h[n - 2] + ... + h[n-1] * h[0];这正是卡特蓝表达式。

h[n] = h[n-1] * (4 * n - 2) / (n + 1).   h[n] = C(2 * n,n)/(n + 1);

对于每一种二叉树,排列的话,需要乘n!.  所以答案为h[n] * n!;

 1 import java.util.*;
 2 import java.io.*;
 3 import java.math.*;
 4 
 5 public class Main
 6 {
 7     public static Scanner cin = new Scanner(new BufferedInputStream(System.in));
 8     public final static int MS= 105;
 9     public final static BigInteger[] h = new BigInteger[MS];
10     public final static BigInteger[] fact = new BigInteger[MS];
11     static
12     {
13         h[0] = BigInteger.ONE;
14         h[1] = BigInteger.ONE;
15         fact[0] = BigInteger.ONE;
16         fact[1] = BigInteger.ONE;
17         for(int i = 2; i < MS; i++)
18         {
19             h[i] = h[i - 1].multiply(BigInteger.valueOf(4 * i - 2)).divide(BigInteger.valueOf(i + 1));
20             fact[i] = fact[i - 1].multiply(BigInteger.valueOf(i));
21         }
22     }
23     public static void main(String[] args)
24     {
25         int n;
26         while(cin.hasNext())
27         {
28             n = cin.nextInt();
29             if(n == 0)
30                 break;
31             System.out.println(h[n].multiply(fact[n]));
32         }
33     }
34 }

 

posted on 2015-08-04 22:06  hutaishi  阅读(241)  评论(0编辑  收藏  举报

导航