#include<iostream>
#include<stack>
#include<map>
#include<limits.h>
using namespace std;
map <string,int> m;
map<int,string>rm;
stack<int>sta;
int P;
int path[40][40];
int d[40][40];
void printpath(int p,int q)
{
while(path[p][q]!=p)
{
sta.push(path[p][q]);
q=path[p][q];
}
while(!sta.empty())
{
cout<<rm[sta.top()]<<" ";
sta.pop();
}
cout<<endl;
}
void f(int p,int q)
{
for(int i=0;i<P;i++)
{
for(int j=0;j<P;j++)
{
if(d[i][j]==INT_MAX)
path[i][j]=-1;
else
path[i][j]=i;
}
}
for(int i=0;i<P;i++)
{
for(int j=0;j<P;j++)
{
for(int k=0;k<P;k++)
{
if(d[i][k]+d[k][j]<d[i][j])
{
d[i][j]=d[i][k]+d[k][j];
path[i][k]=i;
path[i][j]=path[k][j];
}
}
}
}
printpath(p,q);
}
int main()
{
cin>>P;
for(int i=1;i<=P;i++)
{
string a;
cin>>a;
m.insert(pair<string,int>(a,i));
rm.insert(pair<int,string>(i,a));
}
int Q;
cin>>Q;
for(int i=1;i<=P;i++)
{
for(int j=1;j<=P;j++)
{
if(i==j)d[i][j]=0;
else d[i][j]=INT_MAX;
}
}
for(int i=1;i<=Q;i++)
{
string b,c;
int e;
cin>>b>>c>>e;
int f=m[b];
int g=m[c];
d[f][g]=e;
}
int R;
cin>>R;
for(int i=1;i<=R;i++)
{
string h,k;
cin>>h>>k;
int p=m[h];
int q=m[k];
f(p,q);
}
}
#include<stack>
#include<map>
#include<limits.h>
using namespace std;
map <string,int> m;
map<int,string>rm;
stack<int>sta;
int P;
int path[40][40];
int d[40][40];
void printpath(int p,int q)
{
while(path[p][q]!=p)
{
sta.push(path[p][q]);
q=path[p][q];
}
while(!sta.empty())
{
cout<<rm[sta.top()]<<" ";
sta.pop();
}
cout<<endl;
}
void f(int p,int q)
{
for(int i=0;i<P;i++)
{
for(int j=0;j<P;j++)
{
if(d[i][j]==INT_MAX)
path[i][j]=-1;
else
path[i][j]=i;
}
}
for(int i=0;i<P;i++)
{
for(int j=0;j<P;j++)
{
for(int k=0;k<P;k++)
{
if(d[i][k]+d[k][j]<d[i][j])
{
d[i][j]=d[i][k]+d[k][j];
path[i][k]=i;
path[i][j]=path[k][j];
}
}
}
}
printpath(p,q);
}
int main()
{
cin>>P;
for(int i=1;i<=P;i++)
{
string a;
cin>>a;
m.insert(pair<string,int>(a,i));
rm.insert(pair<int,string>(i,a));
}
int Q;
cin>>Q;
for(int i=1;i<=P;i++)
{
for(int j=1;j<=P;j++)
{
if(i==j)d[i][j]=0;
else d[i][j]=INT_MAX;
}
}
for(int i=1;i<=Q;i++)
{
string b,c;
int e;
cin>>b>>c>>e;
int f=m[b];
int g=m[c];
d[f][g]=e;
}
int R;
cin>>R;
for(int i=1;i<=R;i++)
{
string h,k;
cin>>h>>k;
int p=m[h];
int q=m[k];
f(p,q);
}
}