Facing Problem With Trees (卡特兰数变形+java大数)

In this problem you are to find the number (Let P) of ordered trees where each of the tree consists of
exactly m edges and each of the nodes has out-degree either exactly two or zero and the root has even
out-degree. For example, if there are four edges, we get the following three trees.
Input
The first line in the input file is an integer representing the number of test cases. Each of the test cases
follows below. Each case consists an integer representing various even values of m (2 ≤ m ≤ 500).
Output
For each test case, first print the serial number of the case and then print the value of P separated by
an space from the serial number. You should use Big Integer operation to print P and P has maximum
200 digits.
Sample Input
3
4
10
14
Sample Output
Case 1: 3
Case 2: 126
Case 3: 1716

题目大概:

给出n条边,求一棵树,每个结点都要有偶数个边,问有多少种树。

思路:

写出前几个会发现,与卡特兰数有关系。

卡特兰数 1, 1, 2, 5, 14, 42, 

题目数据 1  3  10 35 126 462

     刚好乘   1   3   5   7   9    11

所以直接把数列预处理出来就行了。

代码:


import java.math.*;
import java.util.*;
public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner cin=new Scanner(System.in);
		BigInteger catalan[]=new BigInteger[550];
		catalan[1] = BigInteger.valueOf(1);
		catalan[0] = BigInteger.valueOf(1);
		for(int i=2;i<510;i++)
		{
			BigInteger n=BigInteger.valueOf(i);
			BigInteger sum3=n.add(BigInteger.valueOf(1));
			BigInteger sum1=n.multiply(BigInteger.valueOf(4));
			BigInteger sum2=sum1.subtract(BigInteger.valueOf(2));
			
			BigInteger sum=sum2.multiply(catalan[i-1]);
			catalan[i]=sum.divide(sum3);
			
		}
		for(int i=0;i<510;i++)
		{
			int vv=i+1;
			BigInteger v=BigInteger.valueOf(2*vv-1);
			catalan[i]=catalan[i].multiply(v);
			//System.out.println(catalan[i]);
		}
		int t=cin.nextInt();
		int i=0;
		while(i<t)
		{
			i++;
			int n=cin.nextInt();
			n=n/2;
			n--;
			System.out.println("Case "+i+": "+catalan[n]);
		}
	}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值