1 /*
2 *给出中序和前序,然后构建树,之后遍历树
3 */
4
5 #include <iostream>
6 #include <string>
7 #include<sstream>
8 #include<algorithm>
9 using namespace std;
10
11 const int maxv = 10000+51;
12 int in_order[maxv],post_order[maxv],lch[maxv],rch[maxv];
13 int n;
14
15 bool read_list(int *a){
16 string line;
17 if(!getline(cin,line)) return false;
18 stringstream ss(line);
19 n = 0;
20 int x;
21 while(ss >> x) a[n++] = x;
22 return n > 0;
23 }
24
25 int build(int l1,int r1,int l2,int r2)
26 {
27 if(l1>r1) return 0;
28 int root = post_order[r2];
29 int p = l1;
30 while(in_order[p] != root) p++;
31 int cnt = p - l1;
32 lch[root] = build(l1,p-1,l2,l2+cnt-1);
33 rch[root] = build(p+1,r1,l2+cnt,r2-1);
34 return root;
35 }
36
37 int best,best_sum;
38
39 void dfs(int u,int sum)
40 {
41 sum += u;
42 if(!lch[u] && !rch[u])
43 {
44 if(sum < best_sum || (sum == best_sum && u < best ) )
45 {
46 best = u;
47 best_sum = sum;
48 }
49 }
50 if(lch[u]) dfs(lch[u],sum);
51 if(rch[u]) dfs(rch[u],sum);
52 }
53
54
55 int main()
56 {
57 while(read_list(in_order)){
58 read_list(post_order);
59 build(0 , n - 1 , 0 , n - 1);
60 best_sum = 1000000000;
61 dfs(post_order[n-1],0);
62 cout<<best<<endl;
63 }
64 return 0;
65 }