USACO3.4.2--American Heritage

American Heritage

Farmer John takes the heritage of his cows very seriously. He is not, however, a truly fine bookkeeper. He keeps his cow genealogies as binary trees and, instead of writing them in graphic form, he records them in the more linear `tree in-order' and `tree pre-order' notations.

Your job is to create the `tree post-order' notation of a cow's heritage after being given the in-order and pre-order notations. Each cow name is encoded as a unique letter. (You may already know that you can frequently reconstruct a tree from any two of the ordered traversals.) Obviously, the trees will have no more than 26 nodes.

Here is a graphical representation of the tree used in the sample input and output:

                  C

                /   \

               /     \

              B       G

             / \     /

            A   D   H

               / \

              E   F

The in-order traversal of this tree prints the left sub-tree, the root, and the right sub-tree.

The pre-order traversal of this tree prints the root, the left sub-tree, and the right sub-tree.

The post-order traversal of this tree print the left sub-tree, the right sub-tree, and the root.

PROGRAM NAME: heritage

INPUT FORMAT

Line 1: The in-order representation of a tree.
Line 2: The pre-order representation of that same tree.

SAMPLE INPUT (file heritage.in)

ABEDFCHG

CBADEFGH

OUTPUT FORMAT

A single line with the post-order representation of the tree.

SAMPLE OUTPUT (file heritage.out)

AEFDBHGC 
题解:《算法竞赛入门经典》的106页的《二叉树重建》和此题一模一样,都是已知前序遍历和中序遍历,求后序遍历。因为前序遍历的第一个元素就是二叉树的根,因此只需在中序遍历中找到它,我们就可以知道左子树和右子树的前序遍历和后序遍历了,可以用递归来实现。
直接上书上的代码。。。。
View Code
 1 /*

 2 ID:spcjv51

 3 PROG:heritage

 4 LANG:C

 5 */

 6 #include<stdio.h>

 7 #include<string.h>

 8 #define MAXN 30

 9 char s1[MAXN],s2[MAXN],ans[MAXN];

10 void build(int n,char *s1,char *s2,char *s)

11 {   int p;

12     if(n<=0) return ;

13     p=strchr(s2,s1[0])-s2;

14     build(p,s1+1,s2,s);

15     build(n-p-1,s1+p+1,s2+p+1,s+p);

16     s[n-1]=s1[0];

17 }

18 int main(void)

19 {

20     freopen("heritage.in","r",stdin);

21     freopen("heritage.out","w",stdout);

22     int n;

23     scanf("%s%s",s1,s2);

24     n=strlen(s1);

25     build(n,s2,s1,ans);

26     ans[n]='\0';

27     printf("%s\n",ans);

28     return 0;

29 }

 

 

 

你可能感兴趣的:(USACO)