program ex;
type
data=record
ss:string;
lch,rch,num:longint;
end;
sz=array[1..10000]of data;
var
f:sz;
s:string;
n,m,t,i:longint;
function pd(s1,s2:string):longint;
var
i,l,step:longint;
begin
if length(s1)>length(s2) then l:=length(s2)
else l:=length(s1);
step:=1;pd:=0;
while s1[step]=s2[step] do inc(step);
if s1[step]<s2[step] then pd:=1 else pd:=-1;
end;
begin
assign(input,'scanword.in');
assign(output,'scanword.out');
reset(input);
rewrite(output);
readln(n);
readln(f[1].ss);
readln(f[1].num);
for i:=2 to n do
begin
t:=1;
readln(f[i].ss);readln(f[i].num);
while t<>0 do
begin
if pd(f[t].ss,f[i].ss)>0 then
begin
if f[t].rch<>0 then
begin
t:=f[t].rch;
end
else begin
f[t].rch:=i;
break;
end;
end
else begin
if f[t].lch<>0 then
begin
t:=f[t].lch;
end
else begin
f[t].lch:=i;
break;
end;
end;
end;
end;
readln(m);
for i:=1 to m do
begin
readln(s);
t:=1;
while s<>f[t].ss do
if pd(f[t].ss,s)>0
then t:=f[t].rch
else t:=f[t].lch;
writeln(f[t].num);
end;
close(input);
close(output);
end.