您的位置:首页 > 其它

pku-1095-Trees Made to Order

2008-09-12 12:07 381 查看
考察点:数学,找规律,

思路:先确定N有几个节点,然后确定左右各有多少棵树,及位置编号,用中序遍历打印左右子树

收获:对于边界 要明确,数组是从1开始编号还是从0开始编号,要统一

经验:对于找规律的题目,要善于运用递归等思想去发现规律

ACcode:

#include <iostream>

using namespace  std;

long a[20] = { 1, 1, 2, 5, 14, 42, 132,

429, 1430, 4862, 16796, 58786, 208012,

742900, 2674440, 9694845, 35357670,

129644790, 477638700 };

void solve(int);

void print(long,int);

int main()

{

int n;

cin>>n;

while(n!=0)

{

solve(n);

cin>>n;

}

return 0;

}

void solve(int n)

{

long temp=0;

int nodes=0;

while (temp<=n)

{

temp+=a[nodes++];

}

nodes--;

temp-=a[nodes];

n=n-temp;

print(n,nodes);

cout<<endl;

}

void print(long index,int nodes)

{

if (nodes==1)

{

cout<<"X";

return;

}

long temp=0;

int j=0;

for (int i=0;i<=nodes-1;i++)

{

temp+=a[i]*a[nodes-1-i];

if (temp>index)

{

temp-=a[i]*a[nodes-1-i];

j=i;

break;

}

}

if (j!=0)

{

int pos1=(index-temp)/a[nodes-1-j];

cout<<"(";

print(pos1,j);

cout<<")";

}

cout<<"X";

if (nodes-1-j!=0)

{

int pos2=(index-temp)%a[nodes-1-j];

cout<<"(";

print(pos2,nodes-1-j);

cout<<")";

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: