UVA - 10643 Facing Problem With Trees(卡特兰数变形+高精)

人生中第一道通过的java题。。。写个题解纪念一下

答案就是卡特兰数的变种,可以自己推一下

卡特兰数原理如下:

令h(0)=1,h(1)=1,catalan数满足递推式:
h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)*h(0) (n>=2)
例如:h(2)=h(0)*h(1)+h(1)*h(0)=1*1+1*1=2
h(3)=h(0)*h(2)+h(1)*h(1)+h(2)*h(0)=1*2+1*1+2*1=5
另类递推式:
h(n)=h(n-1)*(4*n-2)/(n+1);
递推关系的解为:
h(n)=C(2n,n)/(n+1) (n=0,1,2,...)
递推关系的另类解为:
h(n)=c(2n,n)-c(2n,n-1)(n=0,1,2,...)

而这道题答案是C(2n+1,n+1)。(n要处理一下)

具体见代码:(第一次写java比较难看。。。)

import java.math.BigInteger;
import java.util.Scanner;


public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        BigInteger [] a = new BigInteger[601];
        BigInteger start = new BigInteger("1");
        BigInteger star = new BigInteger("1");
        a[0] = start;
        a[1] = start;
        for(int i = 2 ; i < 601 ; i ++){
            Integer t1 = i + 1;
            Integer t2 = 4 * i - 2;
            BigInteger k1 = new BigInteger(t1.toString());
            BigInteger k2 = new BigInteger(t2.toString());
            a[i] = (a[i - 1].multiply(k2)).divide(k1);
        }
        while(cin.hasNext()){
           int t = cin.nextInt();
           for (int cas=1;cas<=t;cas++)
           {
            int n = cin.nextInt();
            n = n / 2 - 1;
            int m = 2 * n + 1;
            BigInteger ac = BigInteger.valueOf(m);
            System.out.println("Case "+cas+": "+a[n].multiply(ac));
           }
        }
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值