您的位置:首页 > 其它

Count the Trees 典型卡特兰数

2015-08-04 22:06 302 查看
                      

            Count the Trees

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

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

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

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

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

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

public class Main
{
public static Scanner cin = new Scanner(new BufferedInputStream(System.in));
public final static int MS= 105;
public final static BigInteger[] h = new BigInteger[MS];
public final static BigInteger[] fact = new BigInteger[MS];
static
{
h[0] = BigInteger.ONE;
h[1] = BigInteger.ONE;
fact[0] = BigInteger.ONE;
fact[1] = BigInteger.ONE;
for(int i = 2; i < MS; i++)
{
h[i] = h[i - 1].multiply(BigInteger.valueOf(4 * i - 2)).divide(BigInteger.valueOf(i + 1));
fact[i] = fact[i - 1].multiply(BigInteger.valueOf(i));
}
}
public static void main(String[] args)
{
int n;
while(cin.hasNext())
{
n = cin.nextInt();
if(n == 0)
break;
System.out.println(h
.multiply(fact
));
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: