zoj 1062 Trees Made to Order

ZOJ Problem Set - 1062
Trees Made to Order

Time Limit: 2 Seconds         Memory Limit: 65536 KB

We can number binary trees using the following scheme:

The empty tree is numbered 0.
The single-node tree is numbered 1.
All binary trees having m nodes have numbers less than all those having m+1 nodes.
Any binary tree having m nodes with left and right subtrees L and R is numbered n such that all trees having m nodes numbered > n have either
  Left subtrees numbered higher than L, or
  A left subtree = L and a right subtree numbered higher than R.

The first 10 binary trees and tree number 20 in this sequence are shown below:

zoj <wbr>1062 <wbr>Trees <wbr>Made <wbr>to <wbr>Order

Your job for this problem is to output a binary tree when given its order number.

Input

Input consists of multiple problem instances. Each instance consists of a single integer n, where 1 <= n <= 500,000,000. A value of n = 0 terminates input. (Note that this means you will never have to output the empty tree.)

Output

For each problem instance, you should output one line containing the tree corresponding to the order number for that instance. To print out the tree, use the following scheme:

A tree with no children should be output as X.
A tree with left and right subtrees L and R should be output as (L')X(R'), where L' and R' are the representations of L and R.
  If L is empty, just output X(R').
  If R is empty, just output (L')X.

Sample Input

1
20
31117532
0

Sample Output

X
((X)X(X))X
(X(X(((X(X))X(X))X(X))))X(((X((X)X((X)X)))X)X)


Source: East Central North America 2001
源码:

zoj <wbr>1062 <wbr>Trees <wbr>Made <wbr>to <wbr>Order
zoj <wbr>1062 <wbr>Trees <wbr>Made <wbr>to <wbr>Order
zoj <wbr>1062 <wbr>Trees <wbr>Made <wbr>to <wbr>Order
解题报告:
    题目大意:对于给出的图示二叉树编号,求出给定一个数字,然后输出他的相应的二叉树
    输出格式为(X)
    题目分析:首先看二叉树的构造过程,我们可以发现,结点数再不断的增加,相同结点数的二叉树
    是先从右往左构造,即编号越大的,结点越靠右,此编号过程(相同结点编号)满足catalan数,
    catalan数的递推构造方式:
          h(n)=h(0)*h(n-1)+h(1)*h(n-2)+h(2)*h(n-3)+......
    算法思想:step1:对于给定的一个数,首先根据h(n) 求得他的结点数n,以及在该结点数上的序号x
              step2:得到结点数后,根据以下性质求得左右子树的结点数。性质:以上的catalan数递推
              过程,发现,h(0)*h(n-1)+h(1)*h(n-2)+h(2)*h(n-3)... 其实就是:先h(0)*h(n-1)即左子树为0个
              右子数为n-1个的所有情况,再h(1)*h(n-2) 左子树为1个,右子树为n-1个的所有情况。这种也是以上
              分析的二叉树的编号过程,所以只要用x减去以上h(n)的递推式的每一项,直到小于0,即x-h[i]*h[j]<0
              左右子树即为i,j。
              step3:然后求出左右子树的序号,一般情况,左子树:x/h[j]+1,右子树:x%h[j]+1,这个比较难想,
              需要注意的是,此时的x为左子树为i,右子树为j的第一颗树的序号为1时的相对序号。然后,如果                       xh[j],说明,此时 x-h[j]的即为左子树的增加的序号。
              step4,有了左右子树的结点树和序号,不断递归即可
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值