#include<iostream>
#include<queue>
using namespace std;
const int N=1e4;
bool f1[N];
bool f2[N];
#define MaxInt 1e6
typedef struct{
char ve[N];
int arc[N][N];
int ves,arcs;//顶点数和边长数
}AMGraph;
typedef struct ArcNode{
int adj_vex;
ArcNode *next;
int weight;
}ArcNode;
typedef struct {
char data;
ArcNode* one_arc;
}VNode,AdjList[N];
typedef struct{
AdjList vertices;
int vex_num,arc_num;
}ALGraph;
int LocateVex(AMGraph G,int n){
for(int i=0;i<G.ves;i++) {
if (n==G.ve[i])
return i;
}
return -1;
}
void CreatUDN(AMGraph& G){
cin>>G.ves>>G.arcs;
for(int i=0;i<G.ves;i++){
cin>>G.ve[i];
}
for(int i=0;i<G.ves;i++){
for(int j=0;j<G.ves;j++){
G.arc[i][j]=MaxInt;
}
}
for(int k=0;k<G.arcs;k++){
char v1,v2;
int w;
cin>>v1>>v2>>w;//(输入权值)
auto i=LocateVex(G,v1);
auto j=LocateVex(G,v2);
G.arc[i][j]=w;
G.arc[j][i]=G.arc[i][j];
}
}
int Locate_vex(ALGraph G,int n){
for(int i=0;i<G.vex_num;i++){
if(G.vertices[i].data==n)
return i;
}
return -1;
}
//邻接矩阵储存无向网
void Create_UDN(ALGraph& G){
cin>>G.vex_num>>G.arc_num;
for(int i=0;i<G.vex_num;i++){
cin>>G.vertices[i].data;
G.vertices[i].one_arc=nullptr;
}
for(int k=0;k<G.arc_num;k++){
char v1,v2;
cin>>v1>>v2;
auto i=Locate_vex(G,v1);
auto j=Locate_vex(G,v2);
auto p1=new ArcNode;
p1->adj_vex=j;
p1->next=G.vertices[i].one_arc;
G.vertices[i].one_arc=p1;
auto p2=new ArcNode;
p2->adj_vex=i;
p2->next=G.vertices[j].one_arc;
G.vertices[j].one_arc=p2;
}
}
//建立无向网
void DFS(AMGraph G,int v){
cout<<v<<" ";
f1[v]=true;
for(int w=0;w<G.ves;w++){
if(!f1[w]&&G.arc[v][w]!=0){
f1[w]=true;
DFS(G,w);
}
}
}
void BFS(ALGraph G){
queue<int>q;
for(int i=0;i<G.vex_num;i++){
if(!f2[i]){
f2[i]=true;
q.push(i);
while(q.empty()){
int t=q.front();
q.pop();
cout<<G.vertices[i].data<<" ";
for(auto j=G.vertices[i].one_arc;j!=nullptr;j=j->next){
if(!f2[j->adj_vex]){
f2[j->adj_vex]=true;
q.push(j->adj_vex);
}
}
}
}
}
}
int main(){
AMGraph G1;
ALGraph G2;
CreatUDN(G1);
Create_UDN(G2);
DFS(G1,1);
BFS(G2);
return 0;
}