#include <iostream>
using namespace std;
class node{
public:
int data;
node* left;
node* right;
node(int val){
data = val;
left = NULL;
right = NULL;
}
};
node* buildTree(){
int d;
cin >> d;
if (d == -1){
return NULL;
}
node *root = new node(d);
root->left = buildTree();
root->right = buildTree();
return root;
}
node* find(node* root, int value){
if (root == NULL){
return NULL;
}
if (root->data == value){
return root;
}
node* left = find(root->left, value);
if (left != NULL){
return left;
}
return find(root->right, value);
}
node* buildTreeFromTraversal(int *preorder, int *inorder, int start, int end){
static int i = 0;
if (start > end){
return NULL;
}
node *root = new node(preorder[i]);
int index = -1;
for(int j = start; j <= end; j++){
if (preorder[i] == inorder[j]){
index = j;
}
}
i++;
root->left = buildTreeFromTraversal(preorder, inorder, start, index - 1);
root->right = buildTreeFromTraversal(preorder, inorder, index + 1, end);
return root;
}
void printAtLevelK(node* root, int k){
if (root == NULL){
return;
}
if (k == 0){
cout << root->data << " ";
return;
}
printAtLevelK(root->left, k - 1);
printAtLevelK(root->right, k - 1);
}
int printAtDistancek(node* root, node* target, int k){
//base case
if (root == NULL){
return -1;
}
if (root == target){
printAtLevelK(target, k);
return 0;
}
//when we are at some ancestor node
int leftDistance = printAtDistancek(root->left, target, k);
//if leftDist == -1, then the target is not present
if (leftDistance != -1){
//now there will be 2 more cases
if (leftDistance + 1 == k){
cout << root->data << " ";
} else {
printAtLevelK(root->right, k - 2 - leftDistance);
}
return 1 + leftDistance;
}
int rightDistance = printAtDistancek(root->right, target, k);
if (rightDistance != -1){
if (rightDistance + 1 == k){
cout << root->data << " ";
} else {
printAtLevelK(root->right, k - 2 - rightDistance);
}
return 1 + rightDistance;
}
return -1;
}
int main(){
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int n;
cin >> n;
int preorder[n], inorder[n];
for(int i = 0; i < n; i++){
cin >> preorder[i];
}
for(int i = 0; i < n; i++){
cin >> inorder[i];
}
node* root = buildTreeFromTraversal(preorder, inorder, 0, n - 1);
int t;
cin >> t;
while(t--){
int value, k;
cin >> value >> k;
node* target = find(root, value);
printAtDistancek(root, target, k);
cout << endl;
}
}