poj 1095 Trees Made to Order 卡特兰数

这题用到了卡特兰数,详情见:http://www.cnblogs.com/jackge/archive/2013/05/19/3086519.html

解体思路详见:http://blog.csdn.net/lvlu911/article/details/5425974

代码如下:

 

#include<iostream>

#include<stdio.h>

#include<algorithm>

#include<iomanip>

#include<cmath>

#include<cstring>

#include<vector>

#define ll __int64

#define pi acos(-1.0)

#define MAX 50000

using namespace std;

int an[19]={1,1,2,5,14,42,132,429,1430,4862,16796,58786,208012,

742900,2674440,9694845,35357670,129644790,477638700};

void fun(int n,int k)

{

    if(n==1){

        cout<<'X';

        return;

    }

    int i,sum=0;

    for(i=0;sum<k;i++)

        sum+=an[i]*an[n-i-1];

    i--;

    sum-=an[i]*an[n-i-1];

    k-=sum;

    if(i){

        cout<<'(';

        fun(i,(k-1)/an[n-i-1]+1);

        cout<<')';

    }

    cout<<'X';

    if(n-i-1){

        cout<<'(';

        fun(n-i-1,(k-1)%an[n-i-1]+1);

        cout<<')';

    }

}

int main(){

    int n,m,sum,i;

    while(cin>>n&&n){

        sum=0;

        for(i=1;sum<n;i++)

            sum+=an[i];

        i--;

        fun(i,n-sum+an[i]);

        cout<<endl;

    }

    return 0;

}
View Code

 

 

 

你可能感兴趣的:(order)