#include<bits/stdc++.h>
using namespace std;

vector<int>v; // save in this vector u need to print in sorted order

class node{
    public:
    int data ;
    node*left;
    node*right;

    node( int d){
        data = d;
        left = NULL;
        right = NULL;
    }
};
node*builttree(int*pre,int*in,int s, int e){
	static int i = 0;
	if(s>e){
		return NULL;
	}
	int idx = -1;
	node*root = new node(pre[i]);
	for( int j = s; j<= e; j++){
		if(pre[i] == in[j]){
			idx = j;
			break;
		}
	}
	i++;
	root->left = builttree(pre,in,s,idx-1);
	root->right = builttree(pre,in,idx+1,e);

	return root;
}

node*targetnode(node*root,int A){
	if(root==NULL){
		return NULL;
	}
	node*temp;
	if(root->data == A){
		return root;
	}
	node* ls = targetnode(root->left,A);
	if( ls == NULL){
		return targetnode(root->right,A);
	}
	return ls;
}

void printkthlevel(node*root, int k){
	if(root == NULL){
		return;
	}
	if( k==1 ){
		v.push_back(root->data);
	}
	printkthlevel(root->left,k-1);
	printkthlevel(root->right,k-1);
	return;
}
int printatdistancK(node*root,node*target,int k){
    if(root == NULL){
        return -1;
    }
    //reac the target node
    if(root == target){
        printkthlevel(target,k+1);
        return 0;
    }
    // next step - ancestor
    int DL = printatdistancK(root->left,target,k);
    if(DL!= -1){
        //two cases ancestor or
        if(DL+1 == k){
            v.push_back(root->data);
        }
        else{
            printkthlevel(root->right,k-DL-1);
        }
        return 1+DL;
    }
    int DR = printatdistancK(root->right,target,k);
    if(DR!= -1){
        //two cases ancestor or
        if(DR+1 == k){
            v.push_back(root->data);
        }
        else{
            printkthlevel(root->left,k-DR-1);
        }
        return 1+DR;
    }
    return -1;
}
int main() {
	int n;
	cin >>n;
	int pre[n];
	int in[n];
	for( int i = 0; i<n; i++){
		cin >> pre[i];
	}
	for( int i = 0; i<n; i++){
		cin >>in[i];
	}
	int t;
	cin >> t;
	node*root = builttree(pre,in,0,n-1);
	while(t--){
		int A,k;
		cin >> A>>k;
		node*target = targetnode(root,A);
		printatdistancK(root,target,k);
		if(v.size()==0){
			cout<<0;
		}
        else {
            sort(v.begin(),v.end());
            for(int x : v){
                cout<<x<<" ";
            }
        }
        cout<<endl;
        v.clear(); // clear vector after each test 
		//case as it defined globally so that easily accessible to all function and we dont need to pass all the time
	}
	return 0;
}