catalan卡特兰数:卡塔兰数是组合数学中一个常出现在各种计数问题中出现的数例。由比利时的数学家欧仁·查理·卡塔兰(1814-1894)命名。卡塔兰数的一般公式为 C(2n,n)/(n+1)。
一般计算式为(递归):h(n)=(4n-2)/(n+1)*h(n-1) (n>1),h(0)=1。
计算单个catalan的C++程序:
ll catalan(int n)
{
if(n==0||n==1) return 1;
ll sum=1;
for(int i=2;i<=n;i++)
sum=(4*i-2)*sum/(i+1);
return sum;
}
ll ca[100];
void catalan(int n)
{
ca[0]=ca[1]=1;
for(int i=2;i<=n;i++)
ca[i]=(4*i-2)*ca[i-1]/(i+1);
}
因为第三十项之后catalan数就超long long了,所以附上JAVA大数算的catalan数:
import java.io.*;
import java.math.*;
import java.util.*;
public class Main
{
private static BigInteger four=BigInteger.valueOf(4);
private static BigInteger two=BigInteger.valueOf(2);
private static BigInteger []ca=new BigInteger[105];
public static void catalan(int n)
{
ca[0]=ca[1]=BigInteger.ONE;
for(int i=2;i<=n;i++)
{
BigInteger nn=BigInteger.valueOf(i);
BigInteger mm=(four.multiply(nn)).subtract(two);
BigInteger ii=nn.add(BigInteger.ONE);
ca[i]=(mm.multiply(ca[i-1])).divide(ii);
}
}
public static void main(String[] args)
{
Scanner cin=new Scanner (new BufferedInputStream(System.in));
catalan(100);
while(cin.hasNextInt())
{
int n=cin.nextInt();
System.out.println(ca[n]);
}
}
}
卡特兰数的前几项:1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190, 6564120420, 24466267020, 91482563640, 343059613650, 1289904147324, 4861946401452, …
最常用catalan数的是出栈问题:一个栈(无穷大)的进栈序列为1,2,3,..n,有多少个不同的出栈序列?符合catalan数。
wikioi 1086,3112,3113,3134.
还有2014微软编程之美有道题就是catalan数。