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

class node{
	public:
			int data;
			node* left;
            node* right;
			node(int d){
				data=d;
				left=right=NULL;
			}
};
node* buildtree(int* pre,int* ino,int s,int e){//s & e are indexes of inorder array
	static int i=0;
	if(e<s){
		return NULL;
	}
	node* root=new node(pre[i]);
	int idx=-1;
	for(int j=s;j<=e;j++){
		if(ino[j]==pre[i]){
			idx=j;break;
		}
	}
	i++;
	root->left=buildtree(pre,ino,s,idx-1);
	root->right=buildtree(pre,ino,idx+1,e);
	return root;
}

map<int ,int > visited;
map<node*, node* > parent;
node* target=NULL;

void preorder(node* root,int x){
    if(root==NULL){
        return;
    }
   // cout<<root->data<<" ";
    if(root->data==x){
        target=root;
    }
    if(root->left){                         //making parent map
        parent[root->left]=root;
    }
    if(root->right){
        parent[root->right]=root;
    }
    preorder(root->left,x);
    preorder(root->right,x);
}
void fine(node* root,int level){
	int flag=0;
    queue<pair<node*,int > > q;
    q.push(make_pair(root,0));
    visited[root->data]=1;
    while(!q.empty()){
        pair<node*,int > temp=q.front();
        if(temp.second==level){
        	flag=1;
        	vector<int > v;
        	if(q.empty()){
        		cout<<0<<" ";
        	}
        	else{
	            while(!q.empty()){
	            	v.push_back(q.front().first->data);
	                //cout<<q.front().first->data<<" ";
	                q.pop();
	            }
	            sort(v.begin(),v.end());
	            for(auto it:v){
	            	cout<<it<<" ";
	            }
	            break;
        	}
        }
        q.pop();
        if(temp.first->left && visited[temp.first->left->data]!=1){
            visited[temp.first->left->data]=1;
            q.push(make_pair(temp.first->left,temp.second+1));
        }
        if(temp.first->right && visited[temp.first->right->data]!=1){
            visited[temp.first->right->data]=1;
            q.push(make_pair(temp.first->right,temp.second+1));

        }
        if(parent.find(temp.first)!=parent.end() && visited[parent[temp.first]->data]!=1){
            visited[parent[temp.first]->data]=1;
            q.push(make_pair(parent[temp.first],temp.second+1));

        }
    }
    if(flag==0){
    	cout<<0<<" ";
    }
}

int main(){
	int n,x,y,z;
	cin>>n;
	int a[n+1];
	for(int i=0;i<n;i++)
	{
		cin>>a[i];
	}
	int b[n+1];
	for(int i=0;i<n;i++)
	{
		cin>>b[i];
	}
    node* root=buildtree(a,b,0,n-1);
    cin>>z;
    while(z--){
        cin>>x>>y;
        preorder(root,x);
       // cout<<target->data<<endl;
        fine(target,y)   ;     //node* temp=find(root,x);
		cout<<endl;
		visited.clear();
    }
}
