Trees Made to Order [POJ1095]
http://poj.org/problem?id=1095
catalan数确定N个节点的二叉树的种数,左右分配节点确定id。
View Code
const int MM = 11111; const int maxn = 19; typedef __int64 int64; #define debug puts("wrong") int N; int cata[maxn]; void get_cata() { int i,j,k; cata[0]=cata[1]=1; for(i=2;i<maxn;i++) { for(cata[i]=0,j=0;j<i;j++) cata[i]=cata[i]+cata[j]*cata[i-1-j]; } // for(i=0;i<maxn;i++) printf("%d ",cata[i]); printf("\n"); } void print(int node,int id) { int i,j,k,tmp=0,tt; if(node==1) {printf("X");return;} for(i=0;i<node;i++) { tmp+=cata[i]*cata[node-1-i]; if(tmp>id) break; } tmp-=cata[i]*cata[node-1-i]; if(i!=0) { tt=(id-tmp)/cata[node-1-i]; printf("("); print(i,tt); printf(")"); } printf("X"); if((node-1-i)!=0) { tt=(id-tmp)%cata[node-1-i]; printf("("); print(node-1-i,tt); printf(")"); } } void solve() { int i,j,k,tmp=0; for(i=0;i<maxn;i++) { tmp+=cata[i]; if(tmp>N) break; } tmp-=cata[i]; N-=tmp; // printf("%d %d\n",i,N); print(i,N); printf("\n"); } int main() { get_cata(); while(scanf("%d",&N),N) solve(); return 0; }