火车进出栈问题

卡特兰数应用

求满二叉树有多少种结构,凸多边形三角剖分,在n*n的格子中,只在下三角行走,每次横或竖走一格,有多少中走法,在圆上选择2n个点,将这些点成对连接起来使得所得到的n条线段不相交的方法数,n个长方形填充一个高度为n的阶梯状图形的方法个数

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
//package javaapplication2;

/**
 *
 * @author asus
 */
import java.io.*;
import java.math.*;
import java.util.*;

public class Main {

    static final int maxn = 120050;
    static boolean[] isprime = new boolean[maxn];
    static int[] prime = new int[maxn];
    static int pz = 0;

    static void getPrime() {
        for (int i = 2; i < maxn; ++i) {
            isprime[i] = true;
        }
        for (int i = 2; i < maxn; ++i) {
            if (isprime[i]) {
                prime[pz++] = i;
            }
            for (int j = 0; j < pz && (long) i * prime[j] < maxn; ++j) {
                isprime[i * prime[j]] = false;
                if (i % prime[j] == 0) {
                    break;
                }
            }
        }
    }
    static Scanner cin = new Scanner(System.in);
    static int n = 0;

    public static void main(String[] args) {
        n = cin.nextInt();
        getPrime();
        BigInteger ans=B(1);
        for(int i = 0; i < pz&&prime[i]<=2*n; ++i) {
            int cnt=0,p=prime[i];
            int t=n*2;
            while(t>0) {
                cnt+=t/p;
                t/=p;
            }
            t=n;
            while(t>0) {
                cnt-=t/p*2;
                t/=p;
            }
            ans=ans.multiply(pow(p,cnt));
        }
        System.out.println(ans.divide(B(n+1)));
        
        /*TLE
        BigInteger ans=B(1);
        
        for(int i=1;i<=n;i++) {
            ans=ans.multiply(B(4*i-2)).divide(B(i+1));
        }
        System.out.println(ans);*/
    }

    static BigInteger pow(int x, int n) {
        BigInteger ans = B(1), base = B(x);
        while (n > 0) {
            if (n % 2 == 1) {
                ans = ans.multiply(base);
            }
            base = base.multiply(base);
            n >>= 1;
        }
        return ans;
    }

    static BigInteger B(int x) {
        return BigInteger.valueOf(x);
    }
}

 

你可能感兴趣的:(Catalan,数)