#include <cstdio>
#include <cstring>
const int maxn=100010;
struct NODE{
char data;
int next;
bool flag;
}node[maxn];
int main(){
for(int i=0;i<maxn;i++){
node[i].flag=false;
}
int s1,s2,n; //s1和s2分别代表两条链表的首地址
scanf("%d%d%d",&s1,&s2,&n);
int address,next;
char data;
for(int i=0;i<n;i++){
scanf("%d %c %d",&address,&data,&next);
node[address].data=data;
node[address].next=next;
}
int p;
for(p=s1;p!=-1;p=node[p].next){//遍历第一条链表并赋值flag全为true
node[p].flag=true;
}
/*我的辣鸡代码,判断完true后不需要继续往后遍历
for(p=s2;p!=-1;p=node[p].next){ //遍历判断第二条链表
if(node[p].flag==true){
printf("%05d",p);
}else{
return -1; //傻逼地以为会打印出-1
}
最后还漏了加return 0
*/
for(p=s2;p!=-1;p=node[p].next){
if(node[p].flag==true){
printf("%05d",p);
return 0;
}
}
printf("-1");
return 0;
}