(二叉树)UVA - 548 Tree

又是满满的收获。stringstream,以及根据后序和中序遍历结果求树的方法。

 1 #include <iostream>
 2 #include <string>
 3 #include <algorithm>
 4 #include <cstring>
 5 #include <cstdio>
 6 #include <cmath>
 7 #include <queue>
 8 #include <set>
 9 #include <map>
10 #include <list>
11 #include <stack>
12 #include <sstream>
13 #define mp make_pair
14 typedef long long ll;
15 typedef unsigned long long ull;
16 const int MAX=1e4+5;
17 const int INF=1e9+5;
18 using namespace std;
19 typedef pair<int,int> pii;
20 int in_order[MAX],post_order[MAX],lson[MAX],rson[MAX];
21 int n;
22 bool read(int* a)
23 {
24     string line;
25     if(!getline(cin,line))
26         return false;
27     stringstream ss(line);
28     n=0;int x;
29     while(ss>>x)
30         a[n++]=x;
31     return n>0;
32 }
33 int build(int L1,int R1,int L2,int R2)
34 {
35     if(L1>R1)
36         return 0;
37     int root=post_order[R2];
38     int p=L1;
39     while(in_order[p]!=root)
40         ++p;
41     int cnt=p-L1;
42     lson[root]=build(L1,p-1,L2,L2+cnt-1);
43     rson[root]=build(p+1,R1,L2+cnt,R2-1);
44     return root;
45 }
46 int best,best_sum;
47 void dfs(int u,int sum)
48 {
49     sum+=u;
50     if(!lson[u]&&!rson[u])
51     {
52         if(sum<best_sum||(sum==best_sum&&u<best))
53         {
54             best=u;best_sum=sum;
55         }
56     }
57     if(lson[u])
58         dfs(lson[u],sum);
59     if(rson[u])
60         dfs(rson[u],sum);
61 }
62 int main()
63 {
64     while(read(in_order))
65     {
66         memset(lson,0,sizeof(lson));memset(rson,0,sizeof(rson));
67         read(post_order);
68         build(0,n-1,0,n-1);
69         best_sum=INF;best=INF;
70         dfs(post_order[n-1],0);
71         printf("%d\n",best);
72     }
73 }

 

posted @ 2017-04-15 22:28  perplex  阅读(250)  评论(0编辑  收藏  举报