人生中第一道通过的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));
}
}
}
}