#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <locale.h>
#include <time.h>
typedef struct node Node;
struct node{
Node *g[3];
long val;
int vis;
};
Node *create(long val){
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->val = val;
for(int i = 0; i<3; i++)
newNode->g[i] = NULL;
newNode->vis = 0;
return newNode;
}
void connect(Node *a, Node *b){
if(a->g[0] == NULL)
a->g[0] = b;
else if(a->g[1] == NULL)
a->g[1] = b;
else
a->g[2] = b;
}
bool isSeparator(char c){
return c==' ' || c=='\n' || c=='\r';
}
long wczytNext(){
char c;
while( isSeparator(c = getchar()) )
c = getchar();
if(c==-1)
return -2;
char s[30];
int i = 1;
s[0] = c;
while(!isSeparator(c = getchar())){
s[i++] = c;
}
s[i] = 0;
long ret;
sscanf(s, "%ld", &ret);
return ret;
}
#define N 100000
Node * poziom[N];
int poziomN = 0;
Node * newPoziom[N];
int newPoziomN = 0;
void build(){
newPoziomN = 0;
for(int i = 0; i< poziomN; i++){
long aVal, bVal;
aVal = wczytNext();
bVal = wczytNext();
if(aVal != -1){
Node *a = create(aVal);
connect(a, poziom[i]);
connect(poziom[i], a);
newPoziom[newPoziomN++] = a;
}
if(bVal != -1){
Node *b = create(bVal);
connect(b, poziom[i]);
connect(poziom[i], b);
newPoziom[newPoziomN++] = b;
}
}
for(int i = 0; i<newPoziomN; i++)
poziom[i] = newPoziom[i];
poziomN = newPoziomN;
if(poziomN > 0)
build();
}
int vis[N];
int nextVis = 1;
int d;
Node* dfs(Node *v, long val, int odl){
if(v->val == val){
d = odl;
return v;
}
v->vis = nextVis;
for(int i = 0; i<3; i++){
Node * k = v->g[i];
if(k!=NULL && k->vis != nextVis){
Node * r = dfs(k, val, odl+1);
if(r!=NULL){
return r;
}
}
}
return NULL;
}
// w sumie niepotrzebne
//void clear(Node *v){
// v->vis = nextVis;
// for(int i = 0; i<3; i++){
// Node * k = v->g[i];
// if(k!=NULL && k->vis != nextVis){
// clear(k);
// }
// }
// free(v);
//}
int main()
{
long rootVal = wczytNext();
if(rootVal == -1){
return 0;
}
Node* root = create(rootVal);
poziomN = 1;
poziom[0] = root;
build();
while(true){
long aVal, bVal;
aVal = wczytNext();
if(aVal==-2)
return 0;
bVal = wczytNext();
Node *a = dfs(root,aVal, 0);
nextVis++;
dfs(a,bVal, 0);
nextVis++;
printf("%d ", d);
}
return 0;
}