uva 558 tree(不忍吐槽的题目名)——yhx
来源:互联网 发布:招标文件制作软件 编辑:程序博客网 时间:2024/06/07 13:06
Input
The input file will contain a description of the binary tree given as the inorder and postorder traversal sequences of that tree. Your program will read two line (until end of file) from the input file. The first line will contain the sequence of values associated with an inorder traversal of the tree and the second line will contain the sequence of values associated with a postorder traversal of the tree. All values will be different, greater than zero and less than 10000. You may assume that no binary tree will have more than 10000 nodes or less than 1 node.
Output
For each tree description you should output the value of the leaf node of a path of least value. In the case of multiple paths of least value you should pick the one with the least value on the terminal node.
1 #include<cstdio> 2 #include<cstring> 3 struct node 4 { 5 int lch,rch; 6 }a[10010]; 7 int zx[10010],hx[10010],n,ans=0x7f7f7f7f,ans_leaf=0x7f7f7f7f; 8 bool rdzx() 9 {10 int i,j,k,p,q,x,y,z;11 char c;12 if (scanf("%d",&zx[1])==-1) return 0;13 n=1;14 while (scanf("%c",&c)&&c==' ')15 scanf("%d",&zx[++n]);16 return 1;17 }18 void rdhx()19 {20 int i;21 for (i=1;i<=n;i++)22 scanf("%d",&hx[i]);23 }24 int crt(int lz,int rz,int lh,int rh)25 {26 if (lz>rz) return 0; //注意终止条件27 int i,j,k,p,q,x,y,z;28 p=hx[rh];29 i=lz;30 while (zx[i]!=p) i++;31 a[p].lch=crt(lz,i-1,lh,i+lh-lz-1); //关键在于这两个式子的推导,列方程求比较不费脑子32 a[p].rch=crt(i+1,rz,rh-rz+i,rh-1);33 return p;34 }35 void sc(int p,int x)36 {37 int i,j,k,l,m,y,z;38 x+=p;39 if (!a[p].lch&&!a[p].rch)40 {41 if (x<ans||(x==ans&&p<ans_leaf))42 {43 ans=x;44 ans_leaf=p;45 return;46 }47 }48 if (a[p].lch) sc(a[p].lch,x);49 if (a[p].rch) sc(a[p].rch,x);50 }51 int main()52 {53 int i,j,k,l,m,p,q,x,y,z;54 while (rdzx())55 {56 rdhx();57 memset(a,0,sizeof(a));58 crt(1,n,1,n);59 ans=ans_leaf=0x7f7f7f7f;60 sc(hx[n],0);61 printf("%d\n",ans_leaf);62 }63 }
递归求树,由于后序遍历的最后一个元素一定是根,所以可以在中序中找到根的位置,则其左边为左子树,右边为右子树,分治求解。
求值相对简单,dfs即可。
- uva 558 tree(不忍吐槽的题目名)——yhx
- uva 558 tree(不忍吐槽的题目名)——yhx
- uva 10562 undraw the trees(烂题) ——yhx
- uva 12171 sculpture (超级好题)——yhx
- uva 1599 ideal path(好题)——yhx
- uva 11853 paintball(好题)——yhx
- uva 725 division(水题)——yhx
- uva 11059 maximum product(水题)——yhx
- uva 10976 fractions again(水题)——yhx
- uva 140 bandwidth (好题) ——yhx
- uva 11134 fabled rooks (贪心)——yhx
- uva 10562 undraw the trees(烂题) ——yhx
- uva 12171 sculpture (超级好题)——yhx
- uva 1599 ideal path(好题)——yhx
- uva 11853 paintball(好题)——yhx
- uva 725 division(水题)——yhx
- uva 11059 maximum product(水题)——yhx
- uva 10976 fractions again(水题)——yhx
- vb6.0 Access数据库
- 常用函数(1)
- 1644 免费馅饼 题解(c++)(S.B.S.)
- TYVJ1288 飘飘乎居士取能量块 -SilverN
- uva 122 trees on the level——yhx
- uva 558 tree(不忍吐槽的题目名)——yhx
- uva 839 not so mobile——yhx
- 循环 wxl
- CSS3 之2D变换(旋转,缩放,位移,矩阵函数)
- uva 699 the falling leaves——yhx
- uva 297 quadtrees——yhx
- Java InputStream、String、File相互转化
- uva 572 oil deposits——yhx
- uva 816 abbott's revenge ——yhx