#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
string line;
int in_order[10010],post_order[10010];
struct Node{
Node* left;
Node* right;
int v;
};
Node* create(int l1,int r1,int l2,int r2){
if (l1>r1) return nullptr;
Node* p=(Node*)malloc(sizeof(Node));
p->v=post_order[r2];
int i=l1;
for (; i<=r1; i++)
if (in_order[i]==post_order[r2]) break;
p->left=create(l1, i-1, l2, i-l1+l2-1);
p->right=create(i+1, r1, i-l1+l2, r2-1);
return p;
}
int ans,_min,cur;
void dfs(Node* p){
cur+=p->v;
if (!p->left&&!p->right)
if (cur<_min||(cur==_min&&p->v<ans)) {_min=cur;ans=p->v;}
if (p->left) {dfs(p->left);cur-=p->left->v;}
if (p->right) {dfs(p->right);cur-=p->right->v;}
}
int main() {
while (getline(cin,line)) {
int i=0,x;
stringstream ss1(line);
while (ss1>>x) in_order[i++]=x;
getline(cin,line);i=0;
stringstream ss2(line);
while (ss2>>x) post_order[i++]=x;
Node* root=create(0, i-1, 0, i-1);
ans=_min=0x7fffffff;cur=0;
dfs(root);
printf("%d\n",ans);
}
return 0;
}