您的位置:首页 > 其它

The Falling Leaves(建树方法)

2015-11-28 16:47 435 查看
uva 699

紫书P159

Each year, fall in the North Central region is accompanied by the brilliant colors of the leaves on the trees, followed quickly by the falling leaves accumulating under the trees. If the same thing happened to binary trees, how large would the piles of leaves become?

We assume each node in a binary tree "drops" a number of leaves equal to the integer value stored in that node. We also assume that these leaves drop vertically to the ground (thankfully, there's no wind to blow them around). Finally, we assume that the nodes are positioned horizontally in such a manner that the left and right children of a node are exactly one unit to the left and one unit to the right, respectively, of their parent. Consider the following tree:

#include <iostream>
#include <cstring>
using namespace std;
const int maxn=200;
int sum[maxn];

void Build(int u)
{
int v;
cin>>v;
if(v==-1) return;
sum[u]+=v;
Build(u-1);
Build(u+1);
}

bool Init()
{
memset(sum,0,sizeof(sum));
int v;
cin>>v;
if(v==-1) return false;
int pos=maxn/2;
sum[pos]=v;
Build(pos-1);
Build(pos+1);
}

int ca=1;
void Output()
{
int p=0;
while(sum[p]==0) p++;
cout<<"Case "<<ca++<<":\n"<<sum[p];
while(sum[++p]!=0) {cout<<" "<<sum[p];}
cout<<"\n\n";
}

int main()
{
while(Init())
{
Output();
}
return 0;
}


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