递归构造答案。
根据当前整颗树的编号,可以计算左右子树有几个节点以及编号。因此,不断dfs下去就可以了。
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std; long long c[] = { , , , , , , , , , , , ,
, , , , , };
long long n; void dfs(long long num, long long p)
{
long long left=, right=, sum = ,left_p, right_p;
int level = (int)num;
for (int i = ; i <= level-; i++)
{
sum = sum + c[i] * c[level - - i];
if (sum >= p)
{
sum = sum - c[i] * c[level - - i];
p = p - sum;
left = (long long)i;
right = (long long)(level - - i);
if (c[level - - i] == ) left_p = p / c[level - - i];
else left_p = p / c[level - - i] + ;
right_p = p% c[level - - i];
if (right_p == ) right_p = c[level - - i];
break;
}
} if (left != ){printf("(");dfs(left, left_p);printf(")");}
printf("X");
if (right != ){printf("(");dfs(right, right_p);printf(")");}
} void work()
{
long long p, left, right, sum = ,left_p=, right_p=;
int level;
for (int i = ; i <= ; i++)
{
sum = sum + c[i];
if (sum >= n){ sum = sum - c[i]; level = i; p = n - sum; break; }
}
dfs((long long)level, p);
printf("\n");
} int main()
{
while (~scanf("%lld", &n))
{
if (!n) break;
work();
}
return ;
}