您的位置:首页 > 其它

Uva699 The Falling Leaves

2017-09-22 15:27 411 查看
Eachyear,fallintheNorthCentralregionisaccompaniedbythebrilliantcolorsoftheleavesonthetrees,followedquicklybythefallingleavesaccumulatingunderthetrees.Ifthesamethinghappenedtobinarytrees,howlargewouldthepilesofleavesbecome?

Weassumeeachnodeinabinarytree"drops"anumberofleavesequaltotheintegervaluestoredinthatnode.Wealsoassumethattheseleavesdropverticallytotheground(thankfully,there'snowindtoblowthemaround).Finally,weassumethatthenodesarepositionedhorizontallyinsuchamannerthattheleftandrightchildrenofanodeareexactlyoneunittotheleftandoneunittotheright,respectively,oftheirparent.Considerthefollowingtree:



Thenodescontaining5and6havethesamehorizontalposition(withdifferentverticalpositions,ofcourse).Thenodecontaining7isoneunittotheleftofthosecontaining5and6,andthenodecontaining3isoneunittotheirright.Whenthe"leaves"dropfromthesenodes,threepilesarecreated:theleftmostonecontains7leaves(fromtheleftmostnode),thenextcontains11(fromthenodescontaining5and6),andtherightmostpilecontains3.(Whileitistruethatonlyleafnodesinatreewouldlogicallyhaveleaves,weignorethatinthisproblem.)

Input

Theinputcontainsmultipletestcases,eachdescribingasingletree.Atreeisspecifiedbygivingthevalueintherootnode,followedbythedescriptionoftheleftsubtree,andthenthedescriptionoftherightsubtree.Ifasubtreeisempty,thevalue-1issupplied.Thusthetreeshownaboveisspecifiedas57-16-1-13-1-1.Eachactualtreenodecontainsapositive,non-zerovalue.Thelasttestcaseisfollowedbyasingle-1(whichwouldotherwiserepresentanemptytree).

Output

Foreachtestcase,displaythecasenumber(theyarenumberedsequentially,startingwith1)onalinebyitself.Onthenextlinedisplaythenumberof"leaves"ineachpile,fromlefttoright,withasinglespaceseparatingeachvalue.Thisdisplaymuststartincolumn1,andwillnotexceedthewidthofan80-characterline.Followtheoutputforeachcasebyablankline.Thisformatisillustratedintheexamplesbelow.

SampleInput

57-16-1-13-1-1
829-1-165-1-112-1
-137-1-1-1
-1


SampleOutput

Case1:
7113

Case2:
972115
题意:给一个二叉树,每个节点都有一个水平位置,左子节点在左边1个单位,右子节点在右边一个单位,现在给出前序遍历,求每个水平位置的权值和.
分析:这又是一道递归输入的题目,很显然,我们只需要记录一下当前的节点的位置就好了,这个可以通过递归输入来处理。
这样还有一个问题:根节点的位置不能是0,否则数组会越界.


#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>

usingnamespacestd;

constintmaxn=100010;
intkase,sum[maxn];

voidbuild(intcur)
{
intx;
scanf("%d",&x);
if(x==-1)
return;
sum[cur]+=x;
build(cur-1);
build(cur+1);
}

boolinit()
{
memset(sum,0,sizeof(sum));
intx;
scanf("%d",&x);
if(x==-1)
returnfalse;
intcur=maxn/2;
sum[cur]+=x;
build(cur-1);
build(cur+1);

returntrue;
}

intmain()
{
while(init())
{
printf("Case%d:\n",++kase);
intp=0;
while(!sum[p])
p++;
printf("%d",sum[p++]);
for(inti=p;sum[i];i++)
printf("%d",sum[i]);
printf("\n");
printf("\n");
}

return0;
}



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