【Java練習7——Catalan數】POJ 2084

來源:互聯網
上載者:User

做法:先固定一個點例如1,然後分別連1-2,1-3,1-4.......,這樣線段兩邊各有f1和f2種情況,因此有公式f(n)=f(0)*f(n-2) + f(2)*f(n-4) + f(4)*f(n-8) .....+ f(n-2)*f(0),一看,這就是大名鼎鼎的Catalan數!

令h(1)=1,h(0)=1,Catalan數滿足遞迴式:

h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)h(0) (其中n>=2)

另類遞迴式: 

h(n)=h(n-1)*(4*n-2)/(n+1);  //此題本人採用此公式!

該遞推關係的解為: 

h(n)=C(2n,n)/(n+1) (n=1,2,3,...)

import java.io.*;import java.math.*;import java.util.*;public class Main{public static void main(String[] args){int n;Scanner cin = new Scanner(new BufferedInputStream(System.in));while(cin.hasNext()){n = cin.nextInt();if(n==-1)break;BigInteger a[] = new BigInteger[110];int i;a[0] = a[1] = new BigInteger("1") ;for(i=2;i<=n;i++){a[i] = a[i-1].multiply( BigInteger.valueOf( (4*i-2)) );a[i] = a[i].divide(BigInteger.valueOf(i+1));}System.out.println(a[n]);}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.