卡特兰数

http://acm.hdu.edu.cn/showproblem.php?pid=1023

大意


给定入栈顺序,问合法的出栈顺序有多少个。

思路


卡特兰数,定义进栈为0,出栈为1,那么入栈出栈操作序列又01串组成,那么合法的出栈顺序满足任意前k个序列都满足0的个数大于等于1。这也就是卡特兰数。

ans = \binom{2n}{n}-\binom{2n}{n-1}

code




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

public class Main{
    static int n;
    public static void main(String[] args) {
        Scanner ipt = new Scanner(System.in);
        while(ipt.hasNext()){
            n = ipt.nextInt();
            BigInteger res1 = new BigInteger("1");
            BigInteger res2 = new BigInteger("1");
            BigInteger res3 = new BigInteger("1");
            BigInteger res4 = new BigInteger("1");
            BigInteger ans,ans1;
            for(int i = 1; i <= 2*n; i++){
                res1 = res1.multiply(new BigInteger(String.valueOf(i)));
            }
            for(int i = 1; i <= n; i++){
                if(i < n) res3 = res3.multiply(new BigInteger(String.valueOf(i)));
                res2 = res2.multiply(new BigInteger(String.valueOf(i)));
                res4 = res4.multiply(new BigInteger(String.valueOf(i)));
            }
            res4 = res4.multiply(new BigInteger(String.valueOf(n+1)));
            //System.out.println(res2);
            ans = res1.divide(res2.multiply(res2));
            //System.out.println(ans);
            ans1 = res1.divide(res3.multiply(res4));
            ans = ans.subtract(ans1);
            System.out.println(ans);
        }
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值