现在的位置: 首页 > 综合 > 正文

HDU 1130 How Many Trees? 卡特兰数

2018年01月20日 ⁄ 综合 ⁄ 共 1367字 ⁄ 字号 评论关闭

How Many Trees?

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 2761    Accepted Submission(s): 1619

Problem Description
A binary search tree is a binary tree with root k such that any node v reachable from its left has label (v) <label (k) and any node w reachable from its right has label (w) > label (k). It is a search structure which can find a node
with label x in O(n log n) average time, where n is the size of the tree (number of vertices).
Given a number n, can you tell how many different binary search trees may be constructed with a set of numbers of size n such that each element of the set will be associated to the label of exactly one node in a binary search tree?
Input
The input will contain a number 1 <= i <= 100 per line representing the number of elements of the set.
Output
You have to print a line in the output for each entry with the answer to the previous question.
Sample Input
1 2 3
Sample Output
1 2 5
/*
HDU 1130 How Many Trees? 
据说是卡特兰数,那同1023 
*/
#include<iostream>
using namespace std;
int a[101][101]={0};//a[i]表示的是第i个数 
                    //因为是大数 [j]表示的是这个数的若干位 
int main(){
    int b[101],i,j,n,k,z; 

        a[1][0]=1;
        b[1]=1;
        k=1;//长度 
        for(i=2;i<101;i++)
        {
            for(j=0;j<k;j++)
                a[i][j]=a[i-1][j]*(4*i-2);//乘法大数 每位乘以
            z=0;//进位 
            for(j=0;j<k;j++)
            {
                a[i][j]+=z;
                z=a[i][j]/10;
                a[i][j]%=10;
            } 
            while(z)//仍有进位 
            {
                a[i][k++]=z%10;
                z/=10;
            }
            
            //大数除法 模拟除法 从高到低
            z=0; 
            for(j=k-1;j>=0;j--)
            {
                a[i][j]+=z*10;//上一位剩的
                z=a[i][j]%(i+1);
                a[i][j]/=(i+1);
            } 
            while(!a[i][k-1])//去除前面的0 
                k--;
            b[i]=k; //保存n的大数的长度 
        }
        
        while(cin>>n)
        {
            for(i=b[n]-1;i>=0;i--)
                cout<<a[n][i];
            cout<<endl;
        }     
    return 0;
}

抱歉!评论已关闭.