#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <stack>
#include <cctype>
#include <string>
#include <malloc.h>
#include <map>
using namespace std;
const int Max = 10000+100;
struct Node{
int value;
Node * right;
Node * left;
Node(){
right = left = NULL;
}
};
int in_tree[Max],post_tree[Max];
///a为中序遍历建树那段数组的第一个脚标,///b为后序遍历中根节点的脚标,len为所要建立树的那段数组的长度
void pos_mid_build(Node * &pRoot,int a,int b,int len){
if(len <= 0){
pRoot = NULL;
return;
}
int pos = a;
while(in_tree[pos] != post_tree[b])
pos++;
///在中序遍历中找根节点的位置,根据根节点的位置将中序遍历的数组分成左右子树两部分
int llen = pos - a; /// 左边的长度
int rlen = len - llen - 1; ///右边的长度
pRoot = new Node;
pRoot->value = post_tree[b];
pRoot->right = pRoot->left = NULL;
pos_mid_build(pRoot->left,a,b - rlen - 1,llen);///b-rlen-1是根据下一个根节点在后序遍历数组中的位置
pos_mid_build(pRoot->right,pos+1,b-1,rlen);
return;
}
int best,best_sum;
void dfs(Node * & pNode,int sum){
if(pNode == NULL)
return;
sum += pNode->value;
if(pNode->right == NULL && pNode->left == NULL){
if((sum < best_sum) || (sum == best_sum && pNode->value < best)){
best_sum = sum;
best = pNode->value;
}
}
if(pNode->left != NULL)
dfs(pNode->left,sum);
if(pNode->right != NULL)
dfs(pNode->right,sum);
return;
}
int main()
{
// freopen("inpt.txt","r",stdin);
int tmp;
char ch;
int num;
while(cin >> tmp){
ch = getchar();
num = 0;
in_tree[num++] = tmp;
while(ch != 10){
cin >> tmp;
ch = getchar();
in_tree[num++] = tmp;
}
for(int i = 0;i < num;i++){
cin >> tmp;
post_tree[i] = tmp;
}
Node * root = NULL;
pos_mid_build(root,0,num-1,num);
best_sum = 10e8;
best = -1;
dfs(root,0);
cout << best << endl;
}
return 0;
}