#include<iostream>
using namespace std;
int n = 0, m = 0;
int FindAncestor(int* post, int* in, int a, int b, int size)
{
int root = post[size - 1];
if (root == a || root == b)
return root;
//中序遍历根的下标
int rooti;
for (rooti = 0; rooti < size; rooti++)
{
if (root == in[rooti])
break;
}
//找到a,b在中序遍历的下标
int p = 0, q = 0;
for (int i = 0; i < n; i++)
{
if (a == in[i])
p = i;
if (b == in[i])
q = i;
}
if (p < rooti && q < rooti)
{
FindAncestor(post, in, a, b, rooti);
}
else if (p > rooti && q > rooti)
{
FindAncestor(post + rooti, in + rooti + 1, a, b, size - rooti - 1);
}
else
return in[rooti];
}
bool IsInTree(int* arr, int n, int x)
{
for (int i = 0; i < n; i++)
{
if (x == arr[i])
return true;
}
return false;
}
int main()
{
cin >> n >> m;
int in[10000] = { 0 };
int post[10000] = { 0 };
for (int i = 0; i < n; i++)
cin >> post[i];
for (int i = 0; i < n; i++)
cin >> in[i];
while (m--)
{
int a, b;
cin >> a >> b;
if (!IsInTree(post, n, a) || !IsInTree(post, n, b))
{
cout << "ERROR" << endl;
continue;
}
cout << FindAncestor(post, in, a, b, n) << endl;
}
return 0;
}