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 )); } } }
相关文章推荐
- 【Objective-C编程】import、include及@Class的孽缘
- VistualStudio 2005 设置PowerBuilder12.5 PBNI编绎命令行。
- 浅谈WebView
- Docker 容器日志的那些事儿
- 【Mac版】安装 Android Studio 及配置环境变量步骤
- 没做过编译器就是被人欺——从一道变态的i++题猜编译器的行为(表达式从左往右扫描,同一变量相互影响)
- 关于foreach的一个BUG
- leetcode面试准备:Count Complete Tree Nodes
- Struts拦截器拦截未登录的操作
- sudo 问题
- 黑马程序员--文件字符输入输出函数的应用
- day04_循环结构_20150804
- 获取鼠标XY坐标
- 例子
- FileInputStream与FileOutputStream练习题 -------------------图片拷贝
- Lua在iOS上的编译
- 选数
- uva10392不要被题目骗了,LL质因数分解
- 如何用python实现剔除列表中相同的元素
- win7+opencv2.4.9+visualstudio2013